Flatten JSON in Python

Preview how nested Python dicts become flat path keys before writing a recursive helper, pandas normalization step, or backend import script.

Paste your JSON → Get results instantly (no signup)

⚡ Instant resultsNo signupRuns in your browser
Try examples:

Flatten or nest keys in this JSON structure and flatten nested object.

{
"user": {
"name": "Alice",
"address": {
"city": "NYC",
"zip": "10001"
}
}
}
Output
1{
2 "user.name": "Alice",
3 "user.address.city": "NYC",
4 "user.address.zip": "10001"
5}

Love the result?

Use this exact pipeline in your app, backend, or LLM workflow.

No setup needed. Works with curl, Node, Python.

Uses example data. For edited input, copy from the playground.

Read integration guide

Works with:

  • Python dicts
  • pandas json_normalize comparisons
  • ETL scripts
  • Backend API samples

Example: input → output

Flatten JSON in Python

Python developers usually flatten JSON for one of three reasons: loading nested API data into pandas, exporting records to CSV, or comparing path-level values in an ETL job. A nested dict is great for application code, but a flat path map is easier to put into a DataFrame, fixture, or audit report.

This page lets you preview flattened output before writing Python code. It uses the same engine as the JSON flattener, with examples focused on Python dicts, pandas-style records, and CSV exports.

Python nested dict example

Input:

payload = {
    "user": {
        "id": 7,
        "profile": {
            "email": "ada@example.com",
            "plan": "pro"
        }
    }
}

Flat output:

{
    "user.id": 7,
    "user.profile.email": "ada@example.com",
    "user.profile.plan": "pro"
}

That shape is easier to pass into csv.DictWriter, compare in tests, or inspect as a DataFrame row.

Python flatten helper

def flatten_json(value, prefix="", output=None):
    if output is None:
        output = {}

    if not isinstance(value, dict) or value is None:
        output[prefix] = value
        return output

    for key, child in value.items():
        path = f"{prefix}.{key}" if prefix else key
        flatten_json(child, path, output)

    return output

This simple helper keeps lists intact. If you need indexed paths like items.0.sku, add list handling deliberately or preview array behavior with Flatten JSON Array.

pandas json_normalize vs flattening

pandas.json_normalize() is excellent when your goal is a DataFrame. A JSON flattener is better when you need a general path map, a browser preview, a CSV-ready object, or a language-independent example before writing code.

Use pandas when the next operation is analysis. Use flattening when the next operation is export, diff, documentation, or API debugging. If the result is going to Excel, pair this page with Flatten JSON for CSV.

Common Python mistakes

  • Treating None as an object instead of a leaf value.
  • Flattening lists without deciding whether they should stay lists or become indexed paths.
  • Using dot keys when the original source keys already contain dots.
  • Losing numeric and boolean types by stringifying values too early.
  • Writing a recursive helper before checking what output shape the downstream CSV or API expects.

Frequently asked questions

How do I flatten JSON in Python?+

Use a recursive helper that walks nested dicts, joins keys into a path, and emits primitive values at the leaves. Keep lists intact unless you deliberately want indexed paths.

Is pandas json_normalize the same as flattening JSON?+

pandas json_normalize is a DataFrame-oriented flattening tool. A general JSON flattener creates path-key objects that are useful for CSV, diffs, fixtures, and API debugging.

Should Python flatten arrays by index?+

Only when the destination expects indexed paths. For long arrays, normalize child objects into separate rows instead of creating many columns.

Related tools

Read more on the blog

Advanced usage (optional)

Flatten / Nest

v1.0.0
Structure
objectarrayreversible

Description

Flatten / Nest

Convert between nested and flat object structures. Flatten deep objects into single-level key-value pairs, or nest flat keys back into hierarchical objects. Supports multiple key formats: delimiter-separated, camelCase, snake_case, PascalCase, and kebab-case.

Modes

Flatten

Convert nested objects into flat keys. Each nested path becomes part of the key name.

{ "user": { "name": "Alice" } }  →  { "user.name": "Alice" }

Nest

Convert flat keys back into nested objects by splitting on the delimiter or case boundaries.

{ "user.name": "Alice" }  →  { "user": { "name": "Alice" } }

Key Formats

Delimiter (default)

Join/split key segments with a character (default: .).

  • Flatten: user + nameuser.name
  • Nest: user.nameuser / name

camelCase

Join/split on uppercase letter boundaries.

  • Flatten: user + address + cityuserAddressCity
  • Nest: userAddressCityuser / address / city

snake_case

Join/split on underscores.

  • Flatten: user + address + cityuser_address_city
  • Nest: user_address_cityuser / address / city

PascalCase

Same as camelCase but with uppercase first letter.

  • Flatten: user + nameUserName

kebab-case

Join/split on hyphens.

  • Flatten: user + nameuser-name

Configuration

FieldTypeDefaultDescription
Modeenumflattenflatten or nest
Key Formatenumdelimiterdelimiter, camelCase, snake_case, PascalCase, or kebab-case
Delimiterstring.Character(s) used to join/split key segments (only for delimiter format)
Max Depthnumber0Maximum nesting depth to flatten (0 = unlimited)
Target Pathspath-picker[]Scope operation to specific paths only (empty = apply everywhere)

Use Cases

API Integration

  • Flatten for forms: Convert nested API responses to flat form field names
  • Nest for APIs: Convert flat form data back to nested API request bodies
  • Format conversion: Transform between dot-notation and camelCase conventions

Database Operations

  • MongoDB flattening: Flatten nested documents for tabular export
  • SQL mapping: Convert hierarchical JSON to flat column names for SQL insertion
  • Schema migration: Convert between naming conventions (snake_case ↔ camelCase)

Configuration Management

  • Environment variables: Flatten config objects to dot-notation for .env files
  • Depth limiting: Flatten only the first level while preserving deep structures

Configuration

NameTypeDefaultDescription
Modeenumflattenflatten: convert nested objects to flat keys. nest: convert flat keys back to nested objects. flatten nest
Key Formatenumdelimiterdelimiter: use a character to join/split. Others: camelCase, snake_case, PascalCase, kebab-case. delimiter camelCase snake_case PascalCase kebab-case
Delimiterstring.Character(s) used to join/split key segments (default is dot)
Max Depthnumber0Maximum nesting depth to flatten (0 = unlimited)
Target Pathspath-picker[]Scope operation to specific paths only (empty = apply everywhere)

Examples

AI Prompt
Flatten or nest keys in this JSON structure and flatten nested object.
{
"user": {
"name": "Alice",
"address": {
"city": "NYC",
"zip": "10001"
}
}
}
Output
1{
2 "user.name": "Alice",
3 "user.address.city": "NYC",
4 "user.address.zip": "10001"
5}
Config
Mode
flatten
Delimiter
.
Max Depth
0
Target Paths
all

API Usage

POST /api/v1/utilities/structure.flatten-nest
Example:
curl -X POST https://your-domain.com/api/v1/utilities/structure.flatten-nest \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"inputs":{"primary":{"user":{"name":"Alice","address":{"city":"NYC","zip":"10001"}}}},"config":{"mode":"flatten","delimiter":".","maxDepth":0,"targetPaths":[]}}'
Response
1{
2 "user.name": "Alice",
3 "user.address.city": "NYC",
4 "user.address.zip": "10001"
5}