JSON Flattener
Flatten nested JSON objects into flat key-value pairs. Convert complex JSON to simple format and back.
Data ToolsHow 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
- Paste JSON: Copy and paste your nested JSON object into the input area
- Choose Options: Select separator character and array handling preferences
- Flatten: Click "Flatten" to convert nested JSON to flat key-value pairs
- Unflatten: Click "Unflatten" to reconstruct nested structure from flat JSON
- 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
- Use Examples: Click example buttons to see different flattening scenarios
- Choose Right Separator: Match your use case (. for general, _ for env vars)
- Array Handling: Enable indices for CSV, disable for preserving arrays
- Round Trip: Flatten then unflatten to verify data integrity
- Check Stats: Monitor key count and depth changes
- CSV Export: After flattening, copy to spreadsheet software
- Environment Vars: Use _ separator for .env files
- Database Import: Flatten before bulk insert operations
- Validate JSON: Tool validates JSON during processing
- 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
Related Development Tools
JSON Formatter & Validator
FeaturedFormat, validate, and pretty-print JSON with our developer-friendly editor.
Use Tool βQR Code Generator
FeaturedCreate custom QR codes for URLs, text, and contact info
Use Tool βCSS Beautifier
Format messy CSS into clean, readable styles with consistent indentation and spacing. Perfect for cleaning up minified or poorly formatted stylesheets.
Use Tool βCSV Sorter
Sort CSV by columns - Order CSV rows by one or more columns in ascending or descending order with multi-level sorting support
Use Tool βTSV to CSV Converter
Convert TSV to CSV - Transform tab-separated values to comma-separated values with automatic quoting
Use Tool βCSV to TSV Converter
Convert CSV to TSV - Transform comma-separated values to tab-separated values with automatic quote removal
Use Tool βCSV Column Renamer
Rename CSV columns - Change CSV column headers and standardize naming conventions with camelCase, snake_case, or Title Case
Use Tool βHTTP Status Code Checker
Look up HTTP status codes and their meanings instantly. Understand error codes and how to fix them.
Use Tool βShare Your Feedback
Help us improve this tool by sharing your experience