Pandas Read JSON – How to read in a JSON file in Pandas?

385

Are you figuring out how to read in a JSON file in Pandas? Then, this tutorial will cover it using the read_json() function of Pandas.

Step 1: Prepare your JSON data for Pandas

In most cases, people often fail to create a proper JSON data format and thus, they aren’t able to read JSON files in Pandas.

Here are some key points you have to take in mind for preparing your json file for Pandas:

  1. Make sure the data structure is actually JSON.

Consider you want to import data into a dataframe as shown below:

NameAge
Pamela32
John48
Mary21

Then, the data should be structured in the following way in the JSON file.

{
"Name":{"0":"Pamela","1":"John","2":"Mary"},
"Age":{"0":32,"1":48,"2":21}
}

Notice how the indexes are given as 0,1 and 2 according to their position in the table.

Pandas Read Json - JSON data structure
JSON data structure

2. Make sure the data file is in .json format and not .txt format.

Once you have your data ready, make sure to save it in a .json format.

Save your file as json
Save your json data in .json format

The file should look like this in your system:

data.json file output

Step 2: Use read_json() function in Pandas

Once you have your JSON file ready, you can easily read it in as a dataframe in Pandas using the read_json() function in Pandas.

Syntax:

# Import the Pandas Library as pd
import pandas as pd

# Import using the read_json() function 
pd.read_json('Path where you saved the JSON file\File Name.json')

Example:

Since we had named our JSON file as ‘data.json’ in step 1, we will be reading it in using the read_json function in pandas in the following way:

# Import the Pandas Library as pd
import pandas as pd

# Import using the read_json() function 
df = pd.read_json ('data.json')
print (df)
An example of read_json() function of Pandas

As you can see, it is working! Now, you can perform all sorts of other operations on the JSON data as a Pandas dataframe.

Note: If you have the data.json file in a different folder than where you have your Jupyter Notebook, then, use a full file name such as ‘C:\Users\MSI\Desktop\data.json’.

In Conclusion

We hope that you now know how to read in a JSON file using Pandas.

To learn everything about Pandas, make sure to visit the Pandas Full Course.

LEAVE A REPLY

Please enter your comment!
Please enter your name here