How to Flatten and Parse Deeply Nested JSON in Python, jq, and Node.js
Modern APIs—including Stripe, GitHub, Salesforce, and Kubernetes audit logs—frequently return deeply nested, polymorphic JSON objects. While hierarchical documents are natural for object-oriented application code, loading them into analytical databases (PostgreSQL, BigQuery, Snowflake) or spreadsheet reports requires systematic flattening into a 2-dimensional tabular structure.
In this guide, we examine three production-grade methods for flattening nested JSON payloads using Python, command-line jq, and streaming Node.js, alongside key edge-case strategies for handling nested arrays and key collisions.
1. The Problem: Hierarchical JSON vs. Relational Columns
Consider an enterprise webhook event with nested billing details, address objects, and metadata tags:
{
"event_id": "evt_98214",
"customer": {
"name": "Sarah Connor",
"contact": { "email": "[email protected]", "verified": true }
},
"billing": {
"plan": "Enterprise",
"mrr_usd": 490,
"discounts": [{ "code": "FOUNDER_20", "percent": 20 }]
}
}
To convert this record into CSV or a database table without data loss, we represent parent-child relationships using dot notation: customer.contact.email and billing.plan.
2. Python: Pure Recursive Flattening vs. pandas.json_normalize
For ad-hoc scripts or ETL pipelines, Python provides two solid approaches depending on whether you want a zero-dependency solution or DataFrame integration.
A. Zero-Dependency Recursive Flattener
This pure-Python function traverses arbitrary dictionary depth and joins keys with a configurable separator:
def flatten_dict(d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep=sep).items())
elif isinstance(v, list):
# Flatten primitive lists or serialize array of objects
if all(isinstance(item, (str, int, float, bool)) for item in v):
items.append((new_key, "; ".join(map(str, v))))
else:
items.append((new_key, v))
else:
items.append((new_key, v))
return dict(items)
# Example Usage:
raw_event = {"customer": {"name": "Alex", "geo": {"country": "DE"}}}
print(flatten_dict(raw_event))
# Output: {'customer.name': 'Alex', 'customer.geo.country': 'DE'}
B. Using pandas for Batch Records
When working with thousands of records, pandas.json_normalize applies C-level optimizations:
import json
import pandas as pd
with open("events.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Normalize nested dictionaries into flat columns
df = pd.json_normalize(data, sep='.')
df.to_csv("events_flattened.csv", index=False)
3. Fast CLI Filtering with jq
For DevOps pipelines and shell scripts, jq is unmatched in speed for transforming JSON streams directly on the terminal:
# Un-nest all scalar values into a key-value map using dot paths
cat webhook.json | jq -r '
[paths(scalars) as $p | {
key: ($p | map(tostring) | join(".")),
value: getpath($p)
}] | from_entries
'
4. Node.js Streaming Parser for 500MB+ Payloads
When handling massive multi-gigabyte log dumps in Node.js, loading the entire payload into JSON.parse() will trigger an out-of-memory exception. Instead, use a generator-based line streamer:
import fs from 'node:fs';
import readline from 'node:readline';
function flattenObject(obj, prefix = '', sep = '.') {
const result = {};
for (const [key, val] of Object.entries(obj)) {
const newKey = prefix ? prefix + sep + key : key;
if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
Object.assign(result, flattenObject(val, newKey, sep));
} else {
result[newKey] = Array.isArray(val) ? JSON.stringify(val) : val;
}
}
return result;
}
// Stream JSONL records line by line without memory bloat
const rl = readline.createInterface({
input: fs.createReadStream('heavy_audit.jsonl'),
crlfDelay: Infinity,
});
rl.on('line', (line) => {
if (!line.trim()) return;
const flatRecord = flattenObject(JSON.parse(line));
// Pipe to CSV writer...
});
5. Critical Edge Cases to Plan For
- Arrays of Objects: If a customer has multiple order items, flattening to a single CSV row requires a choice: either duplicate parent attributes (cross-product unnesting) or serialize the item array as a JSON string cell.
- Delimiter Collisions: If object keys contain dots (e.g.,
"user.id"), configure your separator to an underscore (_) or double colon (::) to avoid ambiguous field reconstruction. - RFC-4180 Escaping: Always ensure values containing quotes, line breaks, or commas are wrapped in standard double quotes.
⚡ Need to Convert or Flatten JSON Right Now?
You can run our 100% client-side JSON ↔ CSV Converter directly in your browser. It automatically unwraps nested hierarchies, generates RFC-4180 compliant CSV, and guarantees zero server uploads of your private data.