πŸ”„

JSON Flattener

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

Data ToolsDevelopment
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

πŸ“Ί

Screen Size Converter

710 views

Calculate screen width and height from diagonal size and aspect ratio. Convert between inches and centimeters for displays, TVs, and monitors with instant dimension calculations.

Use Tool β†’
πŸ–¨οΈ

DPI Calculator

290 views

Calculate DPI (dots per inch), image dimensions, and print sizes. Convert between pixels and physical dimensions for printing and displays.

Use Tool β†’
πŸ“„

Paper Size Converter

251 views

Convert between international paper sizes (A4, Letter, Legal) with dimensions in mm, cm, and inches. Compare ISO A/B series and North American paper standards.

Use Tool β†’
β›½

Fuel Consumption Converter

237 views

Convert between MPG (miles per gallon), L/100km (liters per 100 kilometers), and other fuel efficiency units. Compare car fuel economy across different measurement systems.

Use Tool β†’
βœ‚οΈ

CSV Splitter

226 views

Split large CSV files into smaller files by number of rows. Process large datasets in manageable chunks instantly.

Use Tool β†’
πŸ›οΈ

Product Schema Generator

206 views

Generate JSON-LD Product schema markup for SEO. Add product details like name, price, brand, rating, and availability to create structured data for rich search results.

Use Tool β†’
πŸ“„

Large Text File Viewer

175 views

View and search large text files up to 200MB in your browser. Features virtual scrolling, line numbers, search functionality, and file statistics. Perfect for log files, CSV, JSON, and code files.

Use Tool β†’
πŸ”‘

API Key Generator

162 views

Generate secure, cryptographically random API keys for authentication and authorization. Create custom API keys with various formats including hex, base64, and prefixed keys.

Use Tool β†’

Related Development Tools

Share Your Feedback

Help us improve this tool by sharing your experience

We will only use this to follow up on your feedback