jsondecode.com logo

HomeChevronBlogChevronHow to Flatten Nested JSON: Complete Guide

Blog post

How to Flatten Nested JSON: Complete Guide

Flatten deeply nested JSON objects in JavaScript, Python, and more. Code examples, recursive approaches, and libraries explained.

author

Shashank Jain

Author

14/06/20262 minutes 11 seconds read
How to Flatten Nested JSON: Complete GuideHow to Flatten Nested JSON: Complete Guide

Article

What Is JSON Flattening?

Flattening converts a deeply nested JSON object into a single-level object where nested keys become dot-separated paths. This is essential for loading JSON into CSV, relational databases, or flat key-value stores.

// Nested
{
  "user": {
    "name": "Alice",
    "address": { "city": "NYC", "zip": "10001" }
  }
}

// Flattened
{
  "user.name": "Alice",
  "user.address.city": "NYC",
  "user.address.zip": "10001"
}

Recursive Flatten in JavaScript

function flattenJson(obj, prefix = '', separator = '.') {
  return Object.keys(obj).reduce((acc, key) => {
    const newKey = prefix ? `${prefix}${separator}${key}` : key;
    const val = obj[key];

    if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
      Object.assign(acc, flattenJson(val, newKey, separator));
    } else {
      acc[newKey] = val;
    }
    return acc;
  }, {});
}

const nested = {
  a: { b: { c: 1 }, d: 2 },
  e: [1, 2, 3]
};

console.log(flattenJson(nested));
// { 'a.b.c': 1, 'a.d': 2, 'e': [1, 2, 3] }

Flatten in Python

def flatten_json(obj, parent_key='', sep='.'):
    items = []
    for k, v in obj.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_json(v, new_key, sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

nested = {"a": {"b": {"c": 1}, "d": 2}, "e": [1, 2, 3]}
print(flatten_json(nested))
# {'a.b.c': 1, 'a.d': 2, 'e': [1, 2, 3]}

Using Libraries

LanguageLibraryInstall
JavaScriptflatnpm install flat
Pythonflatten-jsonpip install flatten-json
Pythonpandas json_normalizebuilt-in with pandas

pandas json_normalize

import pandas as pd

data = [
  {"user": {"name": "Alice", "city": "NYC"}, "score": 95},
  {"user": {"name": "Bob", "city": "LA"}, "score": 87}
]

df = pd.json_normalize(data)
print(df)
#   user.name user.city  score
# 0     Alice       NYC     95
# 1       Bob        LA     87

Handling Arrays in Flattening

Arrays can be flattened with index-based keys:

function flattenWithArrays(obj, prefix = '') {
  return Object.keys(obj).reduce((acc, key) => {
    const newKey = prefix ? `${prefix}.${key}` : key;
    const val = obj[key];
    if (Array.isArray(val)) {
      val.forEach((item, i) => {
        if (typeof item === 'object') {
          Object.assign(acc, flattenWithArrays(item, `${newKey}[${i}]`));
        } else {
          acc[`${newKey}[${i}]`] = item;
        }
      });
    } else if (val && typeof val === 'object') {
      Object.assign(acc, flattenWithArrays(val, newKey));
    } else {
      acc[newKey] = val;
    }
    return acc;
  }, {});
}

FAQ

How do I unflatten a flattened JSON object?

Reverse the process by splitting keys on the separator and building the nested structure back up. The flat npm package has an unflatten() function. In Python, write a recursive function that splits each key and reconstructs the nesting.

What separator should I use?

Dot (.) is the standard. Use underscore (_) if your keys contain dots. Avoid separators that appear in your key names.

Does flattening lose data?

Arrays are the tricky case. Flattening an array of objects requires choosing a strategy: index-based keys, joining values, or creating multiple rows. No single approach works for all cases.

How deep should I flatten?

Flatten to the depth you need. Most libraries accept a maxDepth option. Flattening too deep can create thousands of columns from large arrays.

Can jsondecode.com flatten JSON?

Use the JSON formatter to inspect structure. For programmatic flattening, use the JavaScript or Python code above.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.