Pandas Read JSON
JSON is a common web data format, and pandas' read_json() function converts it directly into a DataFrame.
Reading JSON Data
JSON (JavaScript Object Notation) stores data as nested key-value pairs, structurally very close to a Python dictionary. The pd.read_json() function accepts a file path, a URL, or a JSON string, and converts it straight into a DataFrame.
Read a JSON File
import pandas as pd
df = pd.read_json('data.json')
print(df.to_string())Reading JSON From a Python Dictionary
If your JSON-like data is already loaded in memory as a Python dictionary, you do not need read_json() at all - pd.DataFrame() converts it directly, since a dictionary of dictionaries maps naturally onto rows and columns.
Convert a Dictionary Directly
import pandas as pd
data = {
"Duration": {"0": 60, "1": 60, "2": 60},
"Pulse": {"0": 110, "1": 117, "2": 103},
"Calories": {"0": 409, "1": 479, "2": 340}
}
df = pd.DataFrame(data)
print(df)- Accepts a file path, a URL, or a raw JSON string
- orient controls how pandas interprets the JSON structure
- lines=True reads newline-delimited JSON (JSON Lines) files
- convert_dates automatically parses date-like columns
Reading JSON Lines Format
Some systems export JSON as one record per line rather than a single array - this format is known as JSON Lines. Set lines=True so pandas parses each line as its own record instead of expecting one big JSON document.
Read a JSON Lines File
import pandas as pd
df = pd.read_json('records.jsonl', lines=True)
print(df.head())Exercise: Pandas Read JSON
Which function reads a JSON file directly into a DataFrame?