The JSON deserialization involves the conversion of JSON objects into their corresponding Python objects. The load() or loads() method is used to deserialize of json objects.
JSON data type is an easy-to-read, flexible text-based format that can save and communicate information to other apps. The JSON module can further accept a JSON string and convert it to a Python dictionary.
JSON Data Structure
The JSON syntax is derived from JavaScript’s object notation syntax:
- Data is in name/value or key/value pairs.
- It is separated by commas.
- The curly braces hold objects.
- The square brackets hold arrays.
The JSON data structure can hold one of the following data types:
- A number
- A string
- An array
- A boolean
- An object (JSON object)
- Null
Python read json file.
To read a JSON file in Python, use the json.load() function. The json.read() function accepts file object, parses the JSON data, and returns a Python dictionary with the data.
Steps to read json file in Python
- Import the json module.
- Open data.json using the with() method.
- Load the JSON object inside the data.json file using the json.load() method.
- Print out the values of the JSON object returned from the load() method.
Syntax
json.load(file_object)
Parameters
The load() method accepts file_object as a parameter and returns a dictionary.
Let’s say we have a JSON file called data.json whose content is the following.
{ "data": [ { "color": "red", "value": "#f00" }, { "color": "green", "value": "#0f0" }, { "color": "blue", "value": "#00f" }, { "color": "black", "value": "#000" } ] }
To work with the JSON object, use Python’s json module.
import json
Now, we will read this file using the json.load() function.
Write the following code inside the app.py file to read json file.
# app.py import json with open('data.json') as f: data = json.load(f) print(data)
Output
{'data': [{'color': 'red', 'value': '#f00'}, {'color': 'green', 'value': '#0f0'}, {'color': 'blue', 'value': '#00f'}, {'color': 'black', 'value': '#000'}]}
Here, we have used the with() function to read the json file. Then, the file is parsed using json.load() method, which gives us a dictionary named data.
Conclusion
If you want to use JSON data from another file or taken as a string format of JSON, then you can deserialize with the load() or loads() method, which is normally used to load from a string. Otherwise, the root object is in a list or dictionary.
That is it for reading json file in Python tutorial.