python

How to read a JSON file in Python

If you have a JSON file on your system and want to read the JSON file and convert the content of the file to Python collection then you can use the methods explained in this post.

import json
 
# open file from a location
fs = open('/usr/data.json')
 
# the result variable will have the Python Collection from file data
result = json.load(fs)

# Close the file
fs.close()
 
# Iterating through the json
for item in result['data']:
    print(item)

We are using the open() function of Python to open a file and get the file object. And then passing the file object to json.load() function. It takes the file object and reads the content of the file and converts it to the Python collection.

if we get the content as a list we can access the element of the file using its index and if the content is in dictionary format then we can access the elements using the key of the dictionary in Python.

You need to import the json module also in your project to use the json.load() function.

Open file in read mode and read JSON data

We can also open the file in reading mode and read JSON data from it if it contains JSON data. If the JSON data is not properly written then will throw an error when calling the function json.load() and passing the file object to it.

import json

# open json file in read format
fs = open('/path/to/data.json', "r")
 
# read data from the file - data.json
result = json.loads(fs.read())

# close the file
fs.close()
 
# loop through json data
for item in result['data']:
    print(item)
Was this helpful?