Categories
Python Answers

How to convert JSON to Pandas DataFrame with Python?

Spread the love

Sometimes, we want to convert JSON to Pandas DataFrame with Python.

In this article, we’ll look at how to convert JSON to Pandas DataFrame with Python.

How to convert JSON to Pandas DataFrame with Python?

To convert JSON to Pandas DataFrame with Python, we can use the json.loads method to load the JSON string into a dictionary.

Then we call Panda’s json_normalize function to convert the JSON to a data frame.

For instance, we write:

import pandas as pd
import json

j = '''
{
    "results": [{
        "elevation": 243.3462677001953,
        "location": {
            "lat": 42.97404,
            "lng": -81.205203
        },
        "resolution": 19.08790397644043
    }, {
        "elevation": 244.1318664550781,
        "location": {
            "lat": 42.974298,
            "lng": -81.19575500000001
        },
        "resolution": 19.08790397644043
    }],
    "status": "OK"
}
'''

data = json.loads(j)
df = pd.json_normalize(data['results'])
print(df)

We call json.loads with the j JSON string to load the JSON string into a dictionary.

Then we call pd.json_normalize with the values we want to convert into a DataFrame and assign that to df.

Therefore, df is:

    elevation  resolution  location.lat  location.lng
0  243.346268   19.087904     42.974040    -81.205203
1  244.131866   19.087904     42.974298    -81.195755

Conclusion

To convert JSON to Pandas DataFrame with Python, we can use the json.loads method to load the JSON string into a dictionary.

Then we call Panda’s json_normalize function to convert the JSON to a data frame.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *