How to read a JSON file in Python

1 min

You will at some point encounter JSON data.

It is the most widely used format for communication and transmission.

There are two ways to read a JSON file that I use most of the time.

It really depends on the structure of the file.

Reading JSON with the JSON library

When I encounter a JSON file that looks like this and is a straight dictionary, I use the JSON library like so

{
    "firstname" : "Brice",
    "lastname" : "Doe",
    "age" : 20,
    "has_siblings" : True,
    "favorite_quote" : """
    The world as we have created it is a process of our thinking.
    It cannot be changed without changing our thinking. Albert Einstein
    """
}
A JSON file that starts with a { or dict format - file.json

and

import json # We import the JSON library

with open("path/to/file.json", "r") as file:
    data = json.load(file) # we load the file to the data variable
    
print(data) # We check the data we have is alright
We read the JSON file

Reading JSON with pandas library

You might encounter other JSON-like formats, like a JSON file containing a list of records. This is often the case when dealing with APIs.

Such file would look like this :

[
{"firstname":"George","lastname":"Dubois"},
{"firstname":"Aman","lastname":"Van Hein"},
{"firstname":"Dennis","lastname":"Washington"},
{"firstname":"John","lastname":"Doe"},
{"firstname":"Foe","lastname":"Less"}
]
A JSON file that looks like a list of records. - file_2.json

Then I would read it like so

import pandas as pd # we import the pandas library to read it as dataframe

df = pd.read_json("path/to/file_2.json") # We read the file as dataframe

print(df) # We print the dataframe object
We read the file_2.json using the Pandas library

Here you are! You are now an expert at reading JSON files.

This can also be applied when you deal with APIs data !