πŸ”„

Flatten Nested JSON to Key-Value Pairs Instantly (Dotted Path Keys)

Flatten nested JSON objects into flat key-value pairs. Convert complex JSON to simple format and back.

Data ToolsData Engineering & Processing
Loading tool...

How to Use JSON Flattener

How to Use JSON Flattener

JSON Flattener is a versatile tool for transforming nested JSON objects into flat key-value pairs and vice versa. Whether you're preparing data for CSV export, simplifying complex structures, or working with databases, this tool makes JSON transformation easy.

Quick Start Guide

  1. Paste JSON: Copy and paste your nested JSON object into the input area
  2. Choose Options: Select separator character and array handling preferences
  3. Flatten: Click "Flatten" to convert nested JSON to flat key-value pairs
  4. Unflatten: Click "Unflatten" to reconstruct nested structure from flat JSON
  5. Copy Output: Click "Copy Output" to copy the result to clipboard

Understanding JSON Flattening

What is JSON Flattening?

JSON flattening transforms nested objects into a flat structure where each nested path becomes a single key using dot notation (or other separators).

Nested JSON:

{ "user": { "name": "John", "age": 30 } }

Flattened JSON:

{ "user.name": "John", "user.age": 30 }

Why Flatten JSON?

  • Convert to CSV format
  • Simplify database operations
  • Easier data processing
  • Better for spreadsheets
  • Reduce complexity

Common Use Cases

1. CSV Export Preparation

Scenario: Export nested JSON data to CSV file.

Input (nested):

{ "user": { "name": "Alice", "email": "alice@example.com" }, "active": true }

Output (flattened):

{ "user.name": "Alice", "user.email": "alice@example.com", "active": true }

Benefit: Each key becomes a CSV column header.

2. Database Import

Scenario: Import nested data into relational database.

Input:

{ "product": { "info": { "name": "Laptop", "price": 999 } } }

Output:

{ "product.info.name": "Laptop", "product.info.price": 999 }

Benefit: Maps to database columns directly.

3. Configuration Management

Scenario: Convert nested config to environment variables.

Input:

{ "database": { "host": "localhost", "port": 5432 } }

Output (with _ separator):

{ "database_host": "localhost", "database_port": 5432 }

Benefit: Matches environment variable naming (DATABASE_HOST).

4. API Response Simplification

Scenario: Simplify complex API responses for frontend.

Input:

{ "data": { "user": { "profile": { "name": "Bob" } } } }

Output:

{ "data.user.profile.name": "Bob" }

Benefit: Easier to access deeply nested values.

5. Array Handling

Scenario: Flatten JSON with arrays.

Input:

{ "user": { "tags": ["admin", "developer"] } }

Output (with array indices):

{ "user.tags.0": "admin", "user.tags.1": "developer" }

Benefit: Each array element becomes a separate key.

6. Data Migration

Scenario: Migrate from nested to flat schema.

Input:

{ "company": { "departments": { "engineering": { "employees": 50 } } } }

Output:

{ "company.departments.engineering.employees": 50 }

Benefit: Easy transition between data structures.

Features

Flatten

  • Convert nested objects to flat structure
  • Configurable key separator
  • Optional array index flattening
  • Preserves data types

Unflatten

  • Reconstruct nested structure
  • Automatic object/array detection
  • Maintains original hierarchy
  • Reverses flattening operation

Separator Options

  • Dot (.) - Standard notation
  • Underscore (_) - Database/env var style
  • Hyphen (-) - Alternative style
  • Slash (/) - Path-like notation

Array Handling

  • Flatten with numeric indices
  • Option to keep arrays intact
  • Supports nested arrays
  • Handles mixed data types

Statistics

  • Total key count
  • Nesting depth
  • Compare input vs output

Technical Details

Flattening Algorithm:

Recursively traverses object tree and builds flat keys:

function flatten(obj, prefix = '') { const result = {} for (const key in obj) { const newKey = prefix ? `${prefix}.${key}` : key if (typeof obj[key] === 'object') { Object.assign(result, flatten(obj[key], newKey)) } else { result[newKey] = obj[key] } } return result }

Unflattening Algorithm:

Splits keys and rebuilds object hierarchy:

function unflatten(obj) { const result = {} for (const key in obj) { const keys = key.split('.') let current = result keys.forEach((k, i) => { if (i === keys.length - 1) { current[k] = obj[key] } else { current[k] = current[k] || {} current = current[k] } }) } return result }

Array Detection:

Numeric keys are converted to array indices:

  • obj.0 β†’ obj[0]
  • obj.1 β†’ obj[1]

Data Type Preservation:

All primitive types are preserved:

  • Strings, numbers, booleans
  • Null and undefined
  • Dates (as ISO strings)

Best Practices

Choosing Separators:

Dot (.) - Best for:

  • General purpose flattening
  • JavaScript object access notation
  • Configuration files

Underscore (_) - Best for:

  • Environment variables
  • Database column names
  • File naming conventions

Hyphen (-) - Best for:

  • URL parameters
  • Configuration keys

Slash (/) - Best for:

  • File paths
  • Hierarchical identifiers

Array Flattening:

With indices (enabled):

{"items.0": "apple", "items.1": "banana"}

Without indices (disabled):

{"items": ["apple", "banana"]}

When to flatten arrays:

  • Converting to CSV (each item = column)
  • Fixed-size arrays
  • Need individual access

When to keep arrays:

  • Variable length data
  • Preserving list structure
  • Dynamic data

Performance Considerations:

Flattening:

  • Fast for objects up to 10,000 keys
  • Handles deep nesting (100+ levels)
  • Minimal memory overhead

Unflattening:

  • Slightly slower than flattening
  • Builds object hierarchy iteratively
  • May require more memory for deep structures

Troubleshooting

Issue: Unflattening creates wrong structure

Solution: Ensure consistent separator used for flattening. If flattened with ".", unflatten with ".".

Issue: Arrays not unflattening correctly

Solution: Use numeric indices when flattening (e.g., "items.0", "items.1"). Enable "Flatten arrays with indices" option.

Issue: Lost data after flatten/unflatten

Solution: Check for conflicting keys. Keys like "user" and "user.name" conflict.

Issue: Special characters in keys

Solution: Avoid using separator character in property names. Use different separator if needed.

Issue: Circular reference error

Solution: JSON cannot represent circular references. Remove circular dependencies before flattening.

Browser Compatibility

This tool works in all modern browsers:

  • βœ… Chrome/Edge (latest)
  • βœ… Firefox (latest)
  • βœ… Safari (latest)
  • βœ… Opera (latest)

Required Features:

  • JavaScript enabled
  • Clipboard API (for copy functionality)

Privacy & Security

Client-Side Processing:

All flattening happens entirely in your browser. Your JSON data:

  • Never leaves your device
  • Is not sent to any server
  • Is not logged or stored
  • Disappears when you close/refresh the page

Safe for Sensitive Data:

You can safely flatten:

  • Database exports
  • Configuration files
  • User data
  • API responses
  • Proprietary data structures

Advanced Use Cases

1. MongoDB to SQL Migration

Flatten nested MongoDB documents for SQL import:

// MongoDB document { "_id": "123", "user": { "profile": { "name": "Alice" } } } // Flattened for SQL { "_id": "123", "user_profile_name": "Alice" }

2. Elasticsearch Mapping

Flatten for Elasticsearch field mapping:

{ "properties.color": "red", "properties.size": "large" }

3. Configuration Files

Convert nested YAML/JSON config to flat env vars:

{ "app_database_host": "localhost", "app_database_port": "5432", "app_cache_enabled": true }

4. Form Data Processing

Flatten nested form data for backend:

{ "user.firstName": "John", "user.lastName": "Doe", "user.address.city": "NYC" }

5. Analytics Data

Flatten event data for analytics platforms:

{ "event.type": "click", "event.target.id": "button1", "event.timestamp": "2024-01-15T10:30:00Z" }

6. CSV Generation

Prepare data for CSV export:

{ "name": "Product A", "details_price": 99.99, "details_stock": 50 }

Real-World Examples

E-commerce Product:

Nested:

{ "product": { "id": 1, "details": { "name": "Laptop", "specs": { "ram": "16GB", "cpu": "i7" } } } }

Flattened:

{ "product.id": 1, "product.details.name": "Laptop", "product.details.specs.ram": "16GB", "product.details.specs.cpu": "i7" }

User Profile:

Nested:

{ "user": { "id": 123, "profile": { "personal": { "name": "Alice", "age": 28 }, "contact": { "email": "alice@example.com" } } } }

Flattened:

{ "user.id": 123, "user.profile.personal.name": "Alice", "user.profile.personal.age": 28, "user.profile.contact.email": "alice@example.com" }

Tips & Tricks

  1. Use Examples: Click example buttons to see different flattening scenarios
  2. Choose Right Separator: Match your use case (. for general, _ for env vars)
  3. Array Handling: Enable indices for CSV, disable for preserving arrays
  4. Round Trip: Flatten then unflatten to verify data integrity
  5. Check Stats: Monitor key count and depth changes
  6. CSV Export: After flattening, copy to spreadsheet software
  7. Environment Vars: Use _ separator for .env files
  8. Database Import: Flatten before bulk insert operations
  9. Validate JSON: Tool validates JSON during processing
  10. Nested Limit: Avoid extreme nesting (100+ levels) for best performance

Common Patterns

Configuration Pattern:

{ "database_host": "localhost", "database_port": 5432, "cache_ttl": 3600 }

Event Tracking Pattern:

{ "event_type": "pageview", "event_page_url": "/products", "user_id": 123 }

API Response Pattern:

{ "data_user_name": "Alice", "data_user_email": "alice@example.com", "metadata_timestamp": "2024-01-15" }

Frequently Asked Questions

Most Viewed Tools

πŸ”

TOTP Code Generator

2,999 views

Generate time-based one-time passwords from a TOTP secret key. Enter your base32 secret, choose a period and digit length, and get the current and next codes with a live countdown timer. Useful for testing and debugging 2FA integrations.

Use Tool β†’
{ }

JSON to Zod Schema Generator

2,983 views

Generate Zod validation schema code from a JSON sample object. Infers z.string(), z.number(), z.boolean(), z.array(), z.object(), and z.null() types automatically. Handles nested objects, arrays of objects with optional field detection, and outputs copy-ready TypeScript with import and z.infer type alias.

Use Tool β†’
{}

JSONL / NDJSON Formatter

2,913 views

Format, validate, and inspect JSON Lines (JSONL) and NDJSON files. Validates each line individually, reports parse errors by line number, outputs compact JSONL or a pretty-print preview, and lets you download the cleaned file.

Use Tool β†’
πŸ”

Secret and Credential Scanner

2,523 views

Scan pasted text, code, or config files for accidentally exposed API keys, tokens, passwords, and private keys. Detects 50+ secret types across AWS, GitHub, Stripe, OpenAI, and more β€” all client-side, nothing leaves your browser.

Use Tool β†’
πŸ”

TLS Cipher Suite Checker

2,493 views

Check TLS protocol version compatibility and cipher suite strength ratings against current best practices. Supports IANA and OpenSSL cipher names β€” rates each suite as Strong, Weak, or Deprecated and explains why.

Use Tool β†’
πŸ”‘

Password Entropy Calculator

2,486 views

Calculate the information-theoretic bit entropy of any password or API key. Detects character set pools automatically, shows the total number of possible combinations, and estimates crack time across five attack scenarios from rate-limited web logins to GPU cracking clusters.

Use Tool β†’
βœ“

TOML Config Validator

2,249 views

Validate TOML configuration file syntax and report errors with line numbers. Paste any TOML content β€” Cargo.toml, pyproject.toml, config.toml β€” and instantly see a green checkmark with key counts and structure stats, or a precise error message pointing to the exact line. Includes a collapsible JSON structure preview to confirm what was parsed.

Use Tool β†’
πŸ”’

Content Security Policy Generator

2,113 views

Build Content Security Policy headers interactively. Toggle directives like script-src, style-src, and img-src, select allowed source tokens, and add custom origins. Instantly outputs your CSP as an HTTP header, meta tag, Nginx directive, or Apache header.

Use Tool β†’

Related Data Engineering & Processing Tools

Share Your Feedback

Help us improve this tool by sharing your experience

We will only use this to follow up on your feedback