JSON Flattener
Flatten nested JSON objects into flat key-value pairs. Convert complex JSON to simple format and back.
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
- 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
Most Viewed Tools
Screen Size Converter
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 βSSH Key Generator
Generate Ed25519 and RSA 4096-bit SSH key pairs entirely in your browser. Keys are never sent to any server β 100% client-side using the Web Crypto API.
Use Tool βPGP Key Generator
Generate PGP public and private key pairs for email encryption and code signing. Supports ECC (Curve25519) and RSA up to 4096-bit. Entirely browser-side β keys never leave your device.
Use Tool βDPI Calculator
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
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 βReorder PDF Pages
Drag and drop to rearrange PDF pages in any order. Upload your PDF, preview all pages as thumbnails, drag pages to reorder them, and download the rearranged PDF. Fast, visual, and privacy-focused.
Use Tool βFuel Consumption Converter
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
Split large CSV files into smaller files by number of rows. Process large datasets in manageable chunks instantly.
Use Tool βRelated Data Engineering & Processing Tools
Dataset Analyzer
FeaturedUpload a CSV, Excel, or JSON file to understand its structure, quality, and patterns. Get column profiles, data quality scores, duplicate detection, outlier analysis, and AI-powered insights β all in your browser.
Use Tool βJSON Formatter & Validator
FeaturedFormat, validate, and pretty-print JSON with our developer-friendly editor.
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 Data Type Converter
Convert data types in CSV - Transform CSV column values to numbers, booleans, dates with automatic type detection and cleaning
Use Tool βCSV to HTML Table
Convert CSV data to HTML table format with customizable styling. Generate clean, semantic table markup instantly.
Use Tool βJSON to XML Converter
Convert JSON data to XML format. Perfect for API integration, data transformation, legacy system compatibility, and SOAP services. Supports nested objects, arrays, and custom formatting.
Use Tool βCSV to Excel Converter
Convert CSV to Excel - Transform comma-separated values to Excel spreadsheet with auto-width columns
Use Tool βXPath Validator
Validate XPath expressions instantly in your browser. Paste an optional XML document to evaluate the expression and see matched nodes. Supports XPath 1.0 with all axes, predicates, and built-in functions.
Use Tool βShare Your Feedback
Help us improve this tool by sharing your experience