AI News
  • Home
  • Artificial Intelligence
  • E-commerce
  • News
  • Featured
  • Web World
  • Contact
No Result
View All Result
AI News
  • Home
  • Artificial Intelligence
  • E-commerce
  • News
  • Featured
  • Web World
  • Contact
No Result
View All Result
AI News
No Result
View All Result

Flatten Nested JSON with pandas: A Troubleshooting Guide

Paul H by Paul H
July 23, 2026
in AI Tools & Automation, Workflow Automation
5 0
0
Flattening nested JSON into a pandas DataFrame using json_normalize
6
SHARES
Summarize with ChatGPTShare to Facebook

The Problem: Real JSON Is Never Flat

If you’ve ever tried to load a nested JSON into a pandas DataFrame, you’ve probably seen something like this:

name address
Alice {‘street’: ‘123 Main’, ‘city’: ‘NYC’}

A column filled with dictionaries. Useless for analysis. Enter json_normalize() — but it’s not magic. This guide tackles the five most frustrating failure modes, with fixes you can copy-paste today.

1. Nested Dictionaries: The Basic Case (and the Trap)

Problem: A simple nested dict seems easy, but json_normalize() flattens only one level by default.

Example:

python
data = [{'name': 'Alice', 'address': {'street': '123 Main', 'city': 'NYC'}}]

Fix: The function works out of the box for one level of nesting.

python
import pandas as pd
pd.json_normalize(data)
name address.street address.city
Alice 123 Main NYC

Trap: If your nested dict has variable keys, json_normalize will still work but may produce NaN for missing keys. That’s expected.

2. Lists of Dictionaries: Use record_path

Problem: When your data has an array of objects, e.g., orders with line items.

python
data = [{'order_id': 1, 'items': [{'product': 'A', 'qty': 2}, {'product': 'B', 'qty': 1}]}]

Fix: Specify record_path to the array key.

python
pd.json_normalize(data, record_path='items')
product qty
A 2
B 1

Problem: Parent fields (like order_id) are lost.

Fix: Add meta parameter.

python
pd.json_normalize(data, record_path='items', meta=['order_id'])
product qty order_id
A 2 1
B 1 1

Trap: If meta key doesn’t exist in every record, you’ll get a KeyError. Use errors='ignore'.

3. Multiple Levels: Nested Arrays Inside Arrays

Problem: Imagine a structure like:

python
data = [{'store': 'NY', 'sales': [{'month': 'Jan', 'details': [{'item': 'shirt', 'revenue': 100}]}]}]

Fix: You cannot flatten more than one record_path directly. Instead, flatten the innermost first, then merge.

python
# Step 1: Flatten innermost
inner = pd.json_normalize(data, record_path=['sales', 'details'], meta=[['sales', 'month']])

# Step 2: Add store from outer with merge (not shown for brevity)

Note: record_path accepts a list of keys to navigate deeper: ['sales', 'details'].

4. Missing Keys: KeyError and NaN Handling

Problem: JSON from APIs often has optional fields.

python
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob'}]

Fix: json_normalize handles missing keys gracefully — it fills with NaN. But if you use meta with a missing key, you get KeyError.

python
pd.json_normalize(data, meta=['name', 'age'])  # No error; age missing becomes NaN

Trap: If the missing key is in a nested dict, e.g., address.street, the errors='ignore' parameter does NOT help. You must handle missing nested values with .get() in a pre-processing step.

5. Arrays That Need explode()

Problem: When record data is not objects but simple values (e.g., tags).

python
data = [{'id': 1, 'tags': ['a', 'b']}]

Fix: json_normalize with record_path works for lists of dicts, not simple lists. Use explode() after normalization.

python
df = pd.DataFrame(data).explode('tags')
id tags
1 a
1 b

Better: If you have multiple columns to keep, normalize first then explode.

6. API Response with a results Key

Problem: APIs commonly wrap data in results.

python
response = {'status': 'ok', 'results': [{'name': 'Alice'}, {'name': 'Bob'}]}

Fix: Access the list directly.

python
pd.json_normalize(response['results'])

But wait — parent metadata? Use meta from the outer dict.

python
pd.json_normalize(response['results'], meta=[['status']])  # Wrong: status is not in results

Correct: meta pulls from the same record, not the outer dict. You need to attach status to each record manually.

python
results = response['results']
for r in results:
    r['status'] = response['status']
pd.json_normalize(results)

Data Table: Common Error Patterns

Error Cause Solution
KeyError: 'address' record_path points to non-existent key Check spelling; ensure key exists in all records
TypeError: string indices must be integers Nested structure is not as expected; maybe you passed a dict instead of list Wrap single dict in a list: [data]
AttributeError: 'list' object has no attribute 'items' record_path is missing; function tried to flatten entire list Specify record_path
Missing parent fields meta not used or path incorrect Use meta=[...]; for nested paths use list of lists: [['parent', 'child']]
ValueError: cannot reindex from a duplicate axis Duplicate names after flattening Add max_level or rename columns

Key Takeaways

  1. Use record_path for lists of dictionaries. Without it, you get one row per outer record, with dicts in cells.
  2. Use meta to preserve parent fields. Pass the list of parent keys you want.
  3. Handle missing keys early. Use Python .get() or try/except before normalizing if you expect missing nested keys.
  4. For multiple nesting levels, flatten innermost first, then merge. One json_normalize per level.
  5. Simple arrays need explode(), not record_path.
  6. Wrapped API results require manual attachment of outer metadata. meta only works within the same record.
  7. max_level controls depth. Default is None (unlimited). Set to 1 to prevent deep flattening.

How to Apply This

Next time you fetch data from an API:

  1. Inspect the JSON structure — print keys and types.
  2. If there’s a list of objects, that’s your record_path.
  3. List the keys you want to keep from parent levels as meta.
  4. Run pd.json_normalize(data, record_path=..., meta=...).
  5. Check for NaN — if unexpected, add error handling.

FAQ

1. Why am I getting a KeyError even though the key exists?

Check if the key is in every record. If one record is missing the key, record_path fails. Use errors='ignore' or filter out those records first.

2. How do I flatten deeply nested JSON with multiple arrays?

Flatten each level sequentially. For example, first flatten the outermost array, then flatten the inner arrays and merge using pd.merge() on a common key.

3. Does json_normalize work with JSON strings?

No, it expects Python dictionaries/lists. Use json.loads() first.

4. Can I flatten only certain fields?

Yes, use max_level to limit depth, then manually select columns. Alternatively, specify meta to include only desired parent fields.

5. What’s the difference between json_normalize and pd.json_normalize?

pd.json_normalize is the modern API (pandas 1.0+). json_normalize is legacy but still works. Use pd.json_normalize.

Conclusion

pd.json_normalize() is powerful but unforgiving. By understanding how record_path, meta, and missing keys interact, you can turn any nested JSON into a clean DataFrame. The next time your API returns a nested mess, you’ll know exactly how to flatten it — without the Google search.

Want more? Check out the official pandas documentation for advanced parameters like sep and max_level.

Related posts:

Zapier vs Make vs n8n for Online Stores

Stores Running Their Own AI Agents Grew 59% Faster

How to Convert Nested JSON to Excel Without Losing Data

Tags: data wranglingflatten JSONjson_normalizeKeyErrornested datapandasPython
SummarizeShare2
Paul H

Paul H

An SEO and Content expert having experience working with Enterprise-level corporations as an SEO and Digital Marketing Specialist. Contact me for any type of SEO/SEM, Digital Marketing service- paul@e-commpartners.com

Related Stories

Studio product photo with a hidden metadata panel, illustrating AI product image disclosure rules

Your AI Product Photos Now Need a Hidden Tag

by Paul H
August 11, 2026
0

Amazon now requires a hidden metadata keyword on any listing image containing a photorealistic AI-generated person. Two more disclosure deadlines landed on August 2.

Parcels flowing back from a storefront into a warehouse under a declining profit line

Return Abuse Costs 6x More Than Return Fraud

by Paul H
July 30, 2026
0

Appriss Retail puts return abuse at $86 billion and outright fraud at $14 billion. Most stores write policy for the smaller number, and it costs them their best...

Illustration of a small cafe counter connected by data lines to floating chat panels, showing AI assistant ordering

Square ChatGPT Ordering Is Live. Are You In?

by Paul H
July 29, 2026
0

Square opted its US restaurant sellers into ChatGPT and Claude ordering on July 1, with no setup and no marketplace commission. Your platform now decides whether AI can...

Illustration of an online storefront receiving a stream of data particles split between human and AI bot traffic

Your Store Is Now the Internet’s Top Bot Target

by Paul H
July 27, 2026
0

Akamai says commerce absorbed 47.9% of AI bot traffic. HUMAN Security says half a percentage point separates a shopping agent from a fraud bot. Here is what to...

Recommended

recaptcha

Google launches reCAPTCHA v3

May 26, 2025
What Your Checkout is Missing

What Your Checkout is Missing: 9 factors

May 26, 2025

Popular Story

  • AI is revolutionizing retail

    The AI Revolution in Retail: Where We Stand Today

    20 shares
    Share 8 Tweet 5
  • Autonomous Deliveries: The Future of eCommerce Logistics and the Rise of Drones and Self-Driving Vehicles

    18 shares
    Share 7 Tweet 5
  • Why use WordPress for your Website?

    17 shares
    Share 7 Tweet 4
  • Top 10 Advanced SEO Techniques & Strategies for 2024

    15 shares
    Share 6 Tweet 4
  • China Opens Car Market after Trump’s action

    14 shares
    Share 6 Tweet 4

E-commerce Partners covers the latest in online retail, AI, and digital shopping trends. We publish news, guides, and analysis to help store owners and marketers stay ahead.

Follow us

Recent Posts

Bar chart of AI impressions next to an empty outline representing missing click data

Your Google AI Impressions Are Live. Clicks Aren’t.

August 2, 2026
Two abstract dashboard panels joined by an arrow, one dissolving into particles, illustrating the Local Services Ads migration into Google Ads

Google Is Erasing Your Local Ads Reports. Export Now

August 2, 2026

Weekly Newsletter

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
No Result
View All Result
  • Landing Page
  • Buy JNews
  • Support Forum
  • Pre-sale Question
  • Contact Us

© 2026 E-commerce Partners - E-commerce & AI news .