AppDividend
Latest Code Tutorials

How to Read JSON File in Python

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.

  1. A number

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

  1. Import the json module.
  2. Open data.json using the with() method.
  3. Load the JSON object inside the data.json file using the json.load() method.
  4. 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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.