Sub topic 1
Flattening Nested JSON into a DataFrame with `json_normalize`
Prerequisites
Assume you know basic Python dictionaries and lists, JSON, and pandas DataFrames. A dictionary is a collection of key-value pairs. A list is an ordered collection of values.
What nested JSON looks like and why it needs flattening
JSON commonly represents an object with nested objects and arrays. In Python, these become dictionaries and lists:
{
"id": 1,
"name": "Ada",
"address": {
"city": "London",
"geo": {"lat": 51.5, "lng": -0.12}
},
"tags": ["python", "data"]
}The address value is a nested object. Its values are several levels below the top level. The tags value is an array. A pandas DataFrame works best when each row represents one record and each column represents one field. Nested values do not initially fit that shape, so flattening converts leaf values into columns.
Getting JSON into Python
Use json.loads when the JSON is text. It parses the text into Python dictionaries and lists.
import json
text = '{"id": 1, "address": {"city": "London"}}'
record = json.loads(text)
print(record["address"]["city"])
# LondonIf a file contains JSON, json.load(file_object) performs the same conversion while reading the file.
Your first `json_normalize` call
pd.json_normalize converts a dictionary, or a list of dictionaries, into a DataFrame.
import pandas as pd
users = [
{
"id": 1,
"name": "Ada",
"address": {"city": "London", "geo": {"lat": 51.5}}
},
{
"id": 2,
"name": "Grace",
"address": {"city": "New York", "geo": {"lat": 40.7}}
},
]
df = pd.json_normalize(users)
print(df.columns.tolist())
# ['id', 'name', 'address.city', 'address.geo.lat']Each user becomes one row. Nested leaf values become columns.
Column names and `sep`
By default, pandas joins nested keys with a period. Pass sep to choose another separator:
df = pd.json_normalize(users, sep="_")
print(df.columns.tolist())
# ['id', 'name', 'address_city', 'address_geo_lat']Choose a separator that does not conflict with your existing field names.
Exercise
What column name does pd.json_normalize create for the value of address["geo"]["lat"] when using the default separator?
Show answer
address.geo.lat.