Python json.load() Method

Python json.load() is a built-in method that accepts a file object and returns the json object. It converts JSON encoded/converted data into Python data types, known as JSON decoding.

Syntax

json.load(file_object)

Parameters

It takes a file object as a parameter.

Mapping between JSON and Python entities while decoding

JSON PYTHON
object dictionary
array list
string str
number (int) int
number (real) float
true True
false False
null None

Let’s follow the below steps to use the json.load() function.

How to load json files in Python

To load json files in Python, you can use the json.load() function. Open a json file using the open() method, create a file object and pass that file object to the json.load() function.

Step 1: Create a JSON file.

To work with json.load() function, create a data.json file.

{
  "data": [
  {
    "color": "red",
    "value": "#f00"
  },
  {
    "color": "green",
    "value": "#0f0"
  },
  {
    "color": "blue",
    "value": "#00f"
  },
  {
    "color": "black",
    "value": "#000"
  }
 ]
}

We will load the data.json file. 

So, in our example, we will load the external json file and convert it into Python types.

Step 2: Open the json file.

To open a file in Python, use the open() method. You can also use with statement to open the file. It returns the file object.

import json

# Opening JSON file
fObj = open('data.json',)

Step 3: Load the file object.

To load the file object, use the json.load() method and pass the file object to the function. The json.load() method returns the dictionary.

# It returns JSON object as dictionary
ogdata = json.load(fObj)
print(ogdata)

The data.json file is filled with an array of objects, meaning when we convert it to the Python data types, we can iterate the dictionary and print the items individually in the console.

{'data': [{'color': 'red', 'value': '#f00'}, 
   {'color': 'green', 'value': '#0f0'}, 
   {'color': 'blue', 'value': '#00f'}, 
   {'color': 'black', 'value': '#000'}
  ]
}

Step 4: Iterate the dictionary data.

We get the dictionary data from json data, and now we can iterate the values, which is the list of dictionaries.

To iterate the list of dictionaries, use the for loop and print the dictionary one by one in the console and then close the file.

import json

# Opening JSON file
fObj = open('data.json',)

# It returns JSON object as dictionary
ogdata = json.load(fObj)

# Iterating through the json list
for i in ogdata['data']:
 print(i)

# Closing file
fObj.close()

If you run the above file, you will see the output below.

{'color': 'red', 'value': '#f00'}
{'color': 'green', 'value': '#0f0'}
{'color': 'blue', 'value': '#00f'}
{'color': 'black', 'value': '#000'}

That’s it.

Leave a Comment

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