Skip to content
Back to Learn
·5 min read

JSON Flattening and Unflattening: A Complete Guide

JSON flattening is the process of converting a nested JSON document into a flat, single-level structure where each leaf value is accessible via a composite key path. Unflattening reverses this process. These techniques are essential for data normalization, CSV export, logging, and working with tabular databases. This guide covers flattening strategies, collision handling, unflattening, and library support across languages. Use our JSON Formatter to examine nested structures before flattening and JSON to CSV to export flattened data.

Why Flatten JSON?

  • CSV/Excel export — Nested JSON must be flattened before saving to tabular formats
  • Log aggregation — Flat documents are easier to index in Elasticsearch/Splunk
  • Database storage — Relational databases require flat columnar structures
  • Data comparison — Flat key-value pairs are easier to diff and patch
  • Form population — HTML form fields use dot notation (e.g., address.city)

Flattening Strategies

StrategySeparatorExampleUse Case
Dot notation.address.cityJavaScript/TypeScript projects
Bracket notation[]address[city]MongoDB/NoSQL queries
Underscore notation_address_citySQL column names
Path separator//address/cityREST API query params

JavaScript Implementation

const nested = {
  name: "Alice",
  address: {
    city: "New York",
    zip: "10001",
    coordinates: { lat: 40.7128, lng: -74.0060 }
  },
  tags: ["json", "flatten", "nested"]
};

// Flatten with dot notation
function flatten(obj, prefix = '', separator = '.') {
  return Object.keys(obj).reduce((acc, key) => {
    const newKey = prefix ? prefix + separator + key : key;
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
      Object.assign(acc, flatten(obj[key], newKey, separator));
    } else {
      acc[newKey] = obj[key];
    }
    return acc;
  }, {});
}

const flat = flatten(nested);
/*
{
  "name": "Alice",
  "address.city": "New York",
  "address.zip": "10001",
  "address.coordinates.lat": 40.7128,
  "address.coordinates.lng": -74.0060,
  "tags": ["json", "flatten", "nested"]
}
*/

Unflattening (Rebuilding Nested Structure)

function unflatten(obj, separator = '.') {
  const result = {};
  for (const key of Object.keys(obj)) {
    const keys = key.split(separator);
    keys.reduce((acc, part, i) => {
      if (i === keys.length - 1) {
        acc[part] = obj[key];
      } else {
        acc[part] = acc[part] || {};
      }
      return acc[part];
    }, result);
  }
  return result;
}

const restored = unflatten(flat);
// Same as original 'nested' object

Python Implementation

def flatten_dict(d, parent_key='', sep='.'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

def unflatten_dict(d, sep='.'):
    result = {}
    for key, value in d.items():
        parts = key.split(sep)
        current = result
        for part in parts[:-1]:
            if part not in current:
                current[part] = {}
            current = current[part]
        current[parts[-1]] = value
    return result

Handling Arrays During Flattening

Arrays need special treatment. Common approaches include:

// Option 1: Index as key part
"tags.0": "json"
"tags.1": "flatten"

// Option 2: Join into string
"tags": "json, flatten, nested"

// Option 3: Keep as array (recommended for performance)
"tags": ["json", "flatten", "nested"]

Collision Handling

What happens when flattening creates duplicate keys? Consider:

{
  "a.b": "value1",
  "a": { "b": "value2" }
}
// Both flatten to "a.b" - collision!

Solutions include: using a different separator that cannot appear in keys, prefixing keys with type information, and using collision detection algorithms. Our JSON Validator can help identify potential collisions before flattening.

Libraries and Tools

LanguageLibraryFunction
JavaScriptflatflatten(nestedObj) / unflatten(flatObj)
Pythonflatten-dictflatten(nested_dict) / unflatten(flat_dict)
JavaApache CommonsMapUtils.flatten(map)
GocustomMost implementations are custom using reflection

Use Cases

  • CSV export: Flatten nested JSON to rows with dot-notation column headers
  • Log shipping: Flatten structured logs to flat key-value pairs for Elasticsearch
  • Form processing: HTML form submits flat data; unflatten to rebuild nested objects
  • API transformation: Some APIs expect flat query params; unflatten on the server
  • Comparison: Use JSON Diff Checker on flattened structures for detailed diffs

Next Steps

Export flattened JSON to CSV with JSON to CSV. Format nested JSON with JSON Formatter. Compare flat structures with JSON Diff Checker.