Reading JSON Files in Pandas
Large datasets are often stored or shared in JSON (JavaScript Object Notation) format. JSON is a plain-text format structured like an object and is widely supported across programming languages — including Python and Pandas.
We'll demonstrate how to read JSON data using Pandas.
Program
Reading a JSON File
Let's load a JSON file named data.json into a Pandas DataFrame:
import pandas as pd
df = pd.read_json('data.json')
print(df.to_string())
Use .to_string() if you want to display the entire DataFrame without truncation.
Using a Dictionary as JSON
In Python, JSON objects closely resemble dictionaries. If your data is not in a .json file but is already available as a Python dictionary, you can load it directly into a DataFrame without saving it to a file.
Program
Loading a Python Dictionary
import pandas as pd
data = {
"Duration": {
"0": 60, "1": 60, "2": 60, "3": 45, "4": 45, "5": 60
},
"Pulse": {
"0": 110, "1": 117, "2": 103, "3": 109, "4": 117, "5": 102
},
"Maxpulse": {
"0": 130, "1": 145, "2": 135, "3": 175, "4": 148, "5": 127
},
"Calories": {
"0": 409, "1": 479, "2": 340, "3": 282, "4": 406, "5": 300
}
}
df = pd.DataFrame(data)
print(df)
This is especially useful when working with APIs or dynamically generated data structures in your Python code.