JSON Flatten

Separator:
Max Depth:(0=unlimited)

Free online JSON flatten & unflatten tool. Convert nested JSON into dot-notation key-value pairs in one click. Custom separators, array-index expansion, and full reverse restoration, all processed locally for better privacy.

Related

Use Cases

  • MongoDB queries and aggregations: convert nested JSON into dot-notation flat structures and use the keys directly in find queries, update statements, and aggregation pipelines—without hand-writing paths
  • CSV/Excel export: flatten multi-level nested objects and use the dot-notation keys as column headers when importing into a Pandas DataFrame or Excel, with one record per row
  • Elasticsearch indexing: flat documents are easier for search engines to store and query—expand nested array fields into single-level key-value pairs
  • API debugging: compare the nested structures of requests and responses side by side; flattened field names are more intuitive and make it easier to spot missing or mis-typed fields
  • Config preprocessing: turn nested configuration files like package.json or settings.json into flat environment-variable form for Docker containers or CI pipelines
  • Logs and monitoring: flatten complex nested log events before writing them into a data warehouse so they can be aggregated and visualized by field

How to Use

  1. Paste the JSON you need to process into the left input box, or click the upload button to pick a local .json file. You can also click the Sample button to load a pre-built nested example
  2. Switch between Flatten and Unflatten mode in the toolbar, then set the separator, array-handling option, and max expansion depth in the options panel below
  3. The tool processes automatically in real time. The right panel instantly shows the result together with key-count and max-depth statistics
  4. Click Copy to put the result on your clipboard, or click Download to save it as a .json file on your device

Features

  • Bidirectional conversion: supports both JSON flatten and unflatten, so you can switch between nested and flat structures losslessly at any time
  • Custom separators: defaults to a dot, but you can switch to underscore, slash, double underscore, or any character to fit different downstream systems
  • Configurable array handling: expand arrays into indexed keys (e.g. items.0, items.1) or keep them as single values to cover both tabular and config-style workflows
  • Max-depth limit: cap the expansion depth to avoid extremely long keys caused by deeply nested structures
  • Real-time statistics: after processing, instantly see the total number of keys and the maximum depth to evaluate output size
  • Local privacy processing: all parsing and conversion happens in the browser, no JSON data is uploaded—ideal for sensitive APIs and production configuration
  • File upload and sample data: upload a .json file or load the built-in sample with one click to quickly verify the conversion
  • Copy and download: copy the result to your clipboard or download it as a standard .json file with a single click for downstream processing

Code Examples

Flatten JSON in JavaScript

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

flatten({ user: { name: 'Alice', contact: { email: 'a@x.com' } } });
// => { 'user.name': 'Alice', 'user.contact.email': 'a@x.com' }

Flatten JSON in Python

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

import json
print(json.dumps(flatten({'user': {'name': 'Alice'}}), indent=2))
# => {"user.name": "Alice"}

Flatten JSON with jq on the command line

bash
# Convert nested JSON to dot-notation flat structure
jq '[paths(scalars) as $p | {"key": $p | join("."), "value": getpath($p)}] | from_entries' data.json

# Reverse a flat JSON back to nested
# Use a third-party filter with jq 1.7+, or simply use the Unflatten mode in this tool.

FAQ

What is JSON flattening and when do I need it?

JSON flattening is the process of converting a multi-level nested object or array into a single-level key-value structure, where nested keys are joined by a separator (default dot). For example, {"user":{"name":"Alice"}} becomes {"user.name":"Alice"}. You need it whenever you want to export nested JSON to CSV, run MongoDB dot queries, build Elasticsearch indexes, flatten configs into environment variables, or feed a downstream system that only accepts flat keys.

Can the flattened JSON be restored back to a nested structure?

Yes. This tool ships with an Unflatten mode. As long as the separator matches, it can losslessly restore flat key-value pairs back to the original nested objects and arrays, and it will automatically detect consecutive integer indices (0, 1, 2…) and reconstruct them as an array—no manual flag required.

Can I customize the separator? How are arrays handled?

Yes. The separator can be a dot, underscore, slash, double underscore, or any character, up to 3 characters long. Arrays have two modes: by default, each element is expanded into a numeric key such as items.0 or items.1; you can also check the option to keep the whole array as a single value. In addition, you can set a max expansion depth (0 means unlimited), and any nesting deeper than that will be preserved as a whole to avoid overly long keys.

Will processing JSON online leak my data?

No. All parsing, flattening, and unflattening happen locally in your browser. The JSON data is never sent to any server. Production APIs, live configuration, and personal data never leave your device, so you can use it with confidence.

How do I use JSON flatten with MongoDB?

MongoDB uses dot-notation to access nested fields by default. For example, to query documents where user.contact.email equals alice@example.com, the command is { "user.contact.email": "alice@example.com" }. After you convert your nested JSON into a dot-notation flat structure with this tool, those keys can be pasted directly into find queries, update statements, or aggregation pipelines, saving you from typing paths by hand.

How do I export flattened JSON to CSV or Excel?

The flattened output is already a single-level key-value structure where every field of a record sits at the same level. You can copy it directly into our JSON to CSV tool, or import it into Excel/Pandas using the dot-notation keys as column headers. For arrays of objects, set a max depth or keep the array as a single value to prevent one record from being split across multiple rows.

When should I use underscore or slash as the separator?

The dot (user.address.city) is the most universal option, well suited for JS objects and MongoDB queries. The underscore (user_address_city) fits SQL column names, Python variable names, and environment variables. The slash (user/address/city) acts like a file path and is common in REST API path parameters. Double underscore (user__address__city) fits Django-style configs that already use single underscores heavily.

What if my key names contain dots or underscores?

That causes a conflict. For example, a key named user.name flattened with a dot separator becomes user.name.name, and unflattening will split it as user → name → name. If your key names contain the separator character, switch to a separator that won't appear in your keys, such as slash or double underscore, or escape the original keys before processing.

How are objects inside arrays expanded?

By default, they are expanded with numeric indices. For example, two objects inside an orders array become orders.0.id, orders.0.total, orders.1.id, orders.1.total. If your downstream consumer expects a one-row-per-record tabular layout, this maps directly to multiple CSV rows. When unflattening, consecutive integer indices (0, 1, 2…) are automatically restored as an array without an extra toggle.

Will very large JSON files freeze the page?

This tool runs in your browser. Typical API responses (tens to hundreds of KB) finish in seconds. For very large files (several MB and above), prefer a local command-line tool such as jq to avoid browser memory pressure. If you must process them online, compress or trim fields first, or split the JSON into batches and flatten them one by one.

What does the max-depth limit do?

The max-depth limit caps expansion at the depth you specify, and any deeper nested objects are kept as a whole single value. It serves two main purposes: first, preventing overly long path keys generated from deeply layered configuration; second, respecting the column-name length limit of downstream databases (some SQL Server columns cap at 128 characters). The default value 0 means unlimited—tune it to fit your case.

Can I save or reuse the converted result?

Yes. After processing you can copy the result to your clipboard with one click, or download it directly as a standard .json file. Everything happens locally, no signup needed, and nothing is cached on the server.

Troubleshooting

Why does it say "Input is not valid JSON"?

Cause: the JSON text contains a syntax error such as missing quotes, stray commas, unmatched brackets, or Python-style booleans (True/False). Fix: validate the JSON with our built-in formatter/validator first. Remember that booleans and null must be lowercase and unquoted, and keys must use double quotes.

Why does unflattening break into the wrong layers after flattening?

Cause: an original key already contains the separator you chose (e.g. user.name flattened with a dot separator). Fix: switch to a separator that does not appear in your keys (slash, double underscore, or a custom character), or rename/escape the original keys before processing.

Why does my array get split into multiple CSV rows?

Cause: by default, array elements are expanded with numeric indices, so each element produces its own set of key-value pairs that get crossed with the other fields into multiple rows. Fix: if you want one row per object, check "Keep array as a single value", or disable expansion for array fields in the CSV tool. If you intentionally want one row per array element, that is the expected behavior.

Why isn't my unflatten result an array?

Cause: only keys that contain consecutive integer indices (0, 1, 2…) are restored as arrays. Keys like orders.first or orders.second will be treated as object keys. Fix: avoid renaming numeric indices during flattening, or manually rewrite the array field's keys to the pure-numeric form (orders.0, orders.1) before unflattening.

Why are my database column names getting truncated?

Cause: deeply nested JSON can produce path keys longer than the column-name limit of downstream databases (such as SQL Server or PostgreSQL). Fix: set a max expansion depth in the options panel—anything deeper will be preserved as a whole; alternatively, restructure the nested data or rename the deep path keys before processing.

Why does the browser freeze or crash on large files?

Cause: very large JSON (tens of MB and above) consumes a lot of browser memory and can leave the page unresponsive. Fix: split the file into smaller chunks, or switch to a command-line tool (jq, flatten-json, Python script). This online tool is best suited for typical API responses, configuration files, and log entries.