Read json data file python

Loading a JSON File in Python – How to Read and Parse JSON

Dillion Megida

Dillion Megida

Loading a JSON File in Python – How to Read and Parse JSON

In this article, you’ll learn how to read and parse JSON in Python.

What is JSON?

JSON is short for JavaScript Object Notation. It’s a simple syntax for storing data in name-value pairs. Values can be different data types as long as they are valid. Non-acceptable types for JSON include functions, dates, and undefined .

JSON files are stored with the .json extension with a valid JSON structure.

Here’s what the structure of a JSON file looks like:

You’ll often use JSON to send and receive data from a server in web applications.

When the data is received, the program reads and parses the JSON to extract specific data. Different languages have their own methods for doing this. We’ll look at how to do these in Python here.

How to Read JSON Files

Let’s say the JSON in the code block above is stored in a user.json file. Using the open() inbuilt function in Python, we can read that file and assign the content to a variable. Here’s how:

with open('user.json') as user_file: file_contents = user_file.read() print(file_contents) #

You pass the file path to the open method which opens the file and assigns the stream data from the file to the user_file variable. Using the read method, you can pass the text contents of the file to the file_contents variable.

I used with at the beginning of the expression so that after reading the contents of the file, Python can close the file.

file_contents now contains a stringified version of the JSON. As a next step, you can now parse the JSON.

How to Parse JSON

Python has in-built modules for various operations. For managing JSON files, Python has the json module.

This module comes with many methods. One of which is the loads() method for parsing JSON strings. Then, you can assign the parsed data to a variable like this:

import json with open('user.json') as user_file: file_contents = user_file.read() print(file_contents) parsed_json = json.loads(file_contents) #

Using the loads() method, you can see that the parsed_json variable now has a valid dictionary. From this dictionary, you can access the keys and values in it.

Also notice how null from the JSON is converted to None in python. This is because null is not valid in Python .

How to Use json.load() to Read and Parse JSON Files

The json module also has the load method which you can use to read a file object and parse it at the same time. Using this method, you can update the previous code to this:

import json with open('user.json') as user_file: parsed_json = json.load(user_file) print(parsed_json) #

Instead of using the read method of the file object and using the loads method of the json module, you can directly use the load method which reads and parses the file object.

Wrapping Up

JSON data is commonly known for its simple structure and is popular (a standard in most cases) for information exchange between servers and clients.

Different languages and technologies can read and parse JSON files in different ways. In this article, we’ve learned how to read JSON files and parse such files using the read method of file objects, and the loads and load methods of the json module.

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Python Parse JSON – How to Read a JSON File

Python Parse JSON – How to Read a JSON File

JSON (JavaScript Object Notation) is a popular way to structure data. It’s used to exchange information between a web application and the server. But how do you read a JSON file in Python?

In this article, I will show you how to use the json.loads() and json.load() methods to parse and read JSON files and strings.

JSON syntax

Before we get into parsing and reading a JSON file, we first need to understand the basic syntax. The JSON syntax looks like a JavaScript object literal with key-value pairs.

This is an example of JSON data for freeCodeCamp:

How to parse a JSON string in Python

Python has a built in module that allows you to work with JSON data. At the top of your file, you will need to import the json module.

If you need to parse a JSON string that returns a dictionary, then you can use the json.loads() method.

import json # assigns a JSON string to a variable called jess jess = '' # parses the data and assigns it to a variable called jess_dict jess_dict = json.loads(jess) # Printed output: print(jess_dict)

How to parse and read a JSON file in Python

In this example, we have a JSON file called fcc.json which holds the same data from earlier concerning the courses offered by freeCodeCamp.

If we want to read that file, we first need to use Python’s built in open() function with the mode of read. We are using the with keyword to make sure that the file is properly closed.

with open('fcc.json', 'r') as fcc_file: 

If the file cannot be opened, then we will receive an OSError. This is an example of a «FileNotFoundError» if I misspell the fcc.json file name.

Screen-Shot-2022-02-07-at-4.47.15-AM

We can then parse the file using the json.load() method and assign it to a variable called fcc_data .

 fcc_data = json.load(fcc_file)

The final step would be to print the results.

This is what the entire code would look like:

import json with open('fcc.json', 'r') as fcc_file: fcc_data = json.load(fcc_file) print(fcc_data)

How to Pretty Print JSON data in Python

If we examine the printed data, then we should see that the JSON data prints all on one line.

Screen-Shot-2022-02-07-at-5.09.05-AM

But that can be hard to read. To fix that, we can use the json.dumps() method with the parameter of indent .

In this example, we are going to have an indent of 4 spaces and print the data in an easier to read format.

 print(json.dumps(fcc_data, indent=4)) 

Screen-Shot-2022-02-07-at-5.13.13-AM

We can also sort the keys in alphabetical order using the sort_keys parameter and setting that to True .

print(json.dumps(fcc_data, indent=4, sort_keys=True)) 

Screen-Shot-2022-02-07-at-5.18.47-AM

Conclusion

JSON (JavaScript Object Notation) is a popular way to structure data and is used to exchange information between a web application and the server.

If you need to parse a JSON string that returns a dictionary, then you can use the json.loads() method.

If you need to parse a JSON file that returns a dictionary, then you can use the json.load() method.

Источник

Read JSON File in Python

Python Certification Course: Master the essentials

JSON (JavaScript Object Notation) is a language-independent data format used to store or represent structured data. A web application and its server can transmit and receive data using the JSON format. Python supports JSON through a built-in package named JSON . To use this functionality, we have to import the JSON package into our python program.

Reading from JSON in Python

Python provides a built-in JSON package, which is used to work with JSON (string, or file containing JSON object). This JSON module provides us with a lot of methods to perform operations such as parse, read and write, etc among which loads() and load() methods are widely used to read JSON files in Python.

In Python, JSON is stored as a string.

The conversion of JSON objects into their respective Python objects is known as Deserialization. We can use load() or loads() method from the python in-built JSON module to deserialize the JSON objects and read JSON file in Python.

The below-given table shows JSON objects and their equivalent Python objects:

Importing JSON Module in Python

To read JSON file in python, we need to import the json module before we can use it. json module makes it easy to parse JSON strings and files containing JSON objects.

Parsing refers to the process of reading data (in formats like strings), analyzing it, and drawing useful inferences from it.

The text in the JSON file is stored using quoted strings which contain the data in key-value pair mapped within <> .

Examples of Reading JSON File in Python

Example 1 : Using json.load() method

json.load() : This method accepts a file object, parses the JSON data, creates a Python dictionary with the data, and returns it back.

Suppose, we have a file named example.json which contains the following JSON object

Below is the implementation of how to read JSON files in python.

Explanation:

In the above program, we used the open() function in python to read JSON file and then parsed the file using json.load() method which gives us data which is of the type dictionary.

If you do not know how to read and write files in Python, you can check How to Read a File in Python.

Example 2: Using json.loads() method

json.loads() : This method does not take the file path, but the contents of a string file as a Python string object and converts it to a python dictionary.

The below program shows how to read JSON files in python from both string and JSON files.

Example 3: Pretty Print JSON in Python

json.dumps() : this method converts a Python object into a JSON string.

After learning how to read json file in python, we have to analyze and debug JSON data, and for this we should print it in a more readable format. This can be done by passing additional parameters indent and sort_keys in json.dumps() method.

In the above program, in json.dumps() method we have set indent=4 , which means 4 spaces of indentation, and sort_keys=True , which means keys are sorted in ascending order.

The default value of indent is None and sort_keys is False.

Conclusion

  • JSON stands for JavaScript Object Notation, and is a file format that stores data. This format helps in storing data and enables communication with servers during deployment
  • The conversion of JSON objects into their respective Python objects is known as Deserialization.
  • Parsing refers to the process of reading data (in formats like strings), analyzing it, and drawing useful inferences from it.
  • We use load() or loads() method from the in-built json module to deserialize the JSON objects and read json file in python.

See Also:

Источник

Читайте также:  Питон windows 10 x64
Оцените статью