Flatten nested JSON to a single level, or unflatten back to nested structure:

Mode:
Loading...
Loading...

What is JSON Flattening?

Flattening converts a nested JSON structure into a single-level object where nested keys are joined with a delimiter. This is useful for data processing, database storage, and CSV export.

Example

Nested JSON:

{
  "user": {
    "name": "John",
    "address": {
      "city": "Boston"
    }
  }
}

Flattened (with dot delimiter):

{
  "user.name": "John",
  "user.address.city": "Boston"
}

Array Handling

Arrays are flattened with bracket notation:

// Input
{
  "tags": ["javascript", "typescript"],
  "users": [
    { "name": "Alice" },
    { "name": "Bob" }
  ]
}

// Output
{
  "tags[0]": "javascript",
  "tags[1]": "typescript",
  "users[0].name": "Alice",
  "users[1].name": "Bob"
}

Delimiter Options

DelimiterExample KeyUse Case
. (dot)user.address.cityMost common, JavaScript-like
/ (slash)user/address/cityPath-like, Firebase RTDB
_ (underscore)user_address_cityEnvironment variables
__ (double)user__address__cityAvoids conflicts with underscores

Common Use Cases

  • CSV export — Flatten before converting to CSV for spreadsheet-friendly data
  • Search indexing — Elasticsearch and other search engines work better with flat documents
  • Key-value stores — Redis, DynamoDB, and similar databases
  • Environment variables — Config management systems
  • Form data — HTML form serialization

Unflatten

The reverse operation reconstructs nested objects from flattened keys. Use this when you need to restore the original structure after processing.

Programmatic Flattening

JavaScript

function flatten(obj, prefix = '', delimiter = '.') {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    const newKey = prefix ? `${prefix}${delimiter}${key}` : key;
    
    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      Object.assign(acc, flatten(value, newKey, delimiter));
    } else {
      acc[newKey] = value;
    }
    
    return acc;
  }, {});
}

Python

def flatten(obj, prefix='', delimiter='.'):
    result = {}
    for key, value in obj.items():
        new_key = f"{prefix}{delimiter}{key}" if prefix else key
        if isinstance(value, dict):
            result.update(flatten(value, new_key, delimiter))
        else:
            result[new_key] = value
    return result

Command Line (with jq)

# Flatten with jq (recursive)
jq '[paths(scalars) as $p | {"key": $p | join("."), "value": getpath($p)}] | from_entries' data.json

Pro Tips

  • 💡 Choose delimiter wisely — If your keys contain dots, use a different delimiter to avoid confusion
  • 💡 Preserve array indices — The bracket notation preserves order when unflattening
  • 💡 Use with CSV — Flatten first, then useJSON to CSV for spreadsheet export

Related Tools