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
| Delimiter | Example Key | Use Case |
|---|---|---|
. (dot) | user.address.city | Most common, JavaScript-like |
/ (slash) | user/address/city | Path-like, Firebase RTDB |
_ (underscore) | user_address_city | Environment variables |
__ (double) | user__address__city | Avoids 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 resultCommand Line (with jq)
# Flatten with jq (recursive)
jq '[paths(scalars) as $p | {"key": $p | join("."), "value": getpath($p)}] | from_entries' data.jsonPro 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
- JSON to CSV — Export flattened data to CSV
- JSON Path — Query nested JSON data
- JSON Validator — Validate your JSON