Home / Guides / Flatten Nested JSON in Python, jq & Node

How to Flatten and Parse Deeply Nested JSON in Python, jq, and Node.js

✍️ By Zain Masri 📅 2026-10-28 ⏱️ 7 min read Data Engineering

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

⚡ 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.

Open Free JSON ↔ CSV Converter →

More Engineering Guides & Tutorials

Security & Auth • 8 min read
Demystifying JSON Web Tokens: Structure, Signature Verification & Security Pitfalls
A practical guide to JSON Web Tokens (JWT): header anatomy, HMAC vs RSA signatures, token tampering prevention, and client-side cryptographic inspection.
Code & Performance • 7 min read
High-Performance Regular Expressions: Preventing ReDoS & Catastrophic Backtracking
Learn how NFA regex engines execute, why nested quantifiers trigger catastrophic backtracking (ReDoS), and how to write linear-time regular expressions.
Architecture & Privacy • 6 min read
Zero-Server Web Architecture: Why In-Browser Processing is Essential for Enterprise Compliance
Why client-side in-browser developer utilities protect corporate data, eliminate third-party leakage vectors, and comply with SOC 2, HIPAA, and GDPR isolation requirements.
⚡ Pro Blueprints ($19) Instant PayPal →