Flattening and Unflattening JSON: A Practical Guide

jsonflattendata-transformationcsv

Flattening JSON converts nested objects into dot-notation keys. This is essential for databases, spreadsheets, and certain API formats.

What is JSON Flattening?

Nested JSON:

{

"user": {

"name": "Alice",

"address": {

"city": "New York",

"zip": "10001"

}

},

"tags": ["admin", "dev"]

}

Flattened:

{

"user.name": "Alice",

"user.address.city": "New York",

"user.address.zip": "10001",

"tags.0": "admin",

"tags.1": "dev"

}

Flatten Implementation

function flatten(obj, prefix = '') {

const result = {};

for (const [key, value] of Object.entries(obj)) {

const newKey = prefix ? ${prefix}.${key} : key;

if (value && typeof value === 'object' && !Array.isArray(value)) {

Object.assign(result, flatten(value, newKey));

} else {

result[newKey] = value;

}

}

return result;

}

Unflatten Implementation

function unflatten(obj) {

const result = {};

for (const [key, value] of Object.entries(obj)) {

const keys = key.split('.');

let current = result;

for (let i = 0; i < keys.length - 1; i++) {

current[keys[i]] = current[keys[i]] || {};

current = current[keys[i]];

}

current[keys[keys.length - 1]] = value;

}

return result;

}

Use Cases

  • CSV Export — Flatten before converting to CSV rows
  • Database Storage — Store nested data in flat columns
  • Form Data — Convert form fields to nested objects
  • Translation Files — Flat keys are easier to manage
  • Environment Variables — Use __ or _ as separator
  • Handling Arrays

    Arrays can use numeric indices or bracket notation:

    // Index notation: "items.0.name"

    // Bracket notation: "items[0].name"

    Choose one convention and stick with it.

    Use our JSON to CSV converter to export flattened JSON to spreadsheets.

    Related Tools