Flatten JSON in Python
Preview how nested Python dicts become flat path keys before writing a recursive helper, pandas normalization step, or backend import script.
Paste your JSON → Get results instantly (no signup)
→ Flatten or nest keys in this JSON structure and flatten nested object.
1{2 "user.name": "Alice",3 "user.address.city": "NYC",4 "user.address.zip": "10001"5}Love the result?
Use this exact pipeline in your app, backend, or LLM workflow.
No setup needed. Works with curl, Node, Python.
Uses example data. For edited input, copy from the playground.
Works with:
- Python dicts
- pandas json_normalize comparisons
- ETL scripts
- Backend API samples
Example: input → output
Flatten JSON in Python
Python developers usually flatten JSON for one of three reasons: loading nested API data into pandas, exporting records to CSV, or comparing path-level values in an ETL job. A nested dict is great for application code, but a flat path map is easier to put into a DataFrame, fixture, or audit report.
This page lets you preview flattened output before writing Python code. It uses the same engine as the JSON flattener, with examples focused on Python dicts, pandas-style records, and CSV exports.
Python nested dict example
Input:
payload = {
"user": {
"id": 7,
"profile": {
"email": "ada@example.com",
"plan": "pro"
}
}
}Flat output:
{
"user.id": 7,
"user.profile.email": "ada@example.com",
"user.profile.plan": "pro"
}That shape is easier to pass into csv.DictWriter, compare in tests, or inspect as a DataFrame row.
Python flatten helper
def flatten_json(value, prefix="", output=None):
if output is None:
output = {}
if not isinstance(value, dict) or value is None:
output[prefix] = value
return output
for key, child in value.items():
path = f"{prefix}.{key}" if prefix else key
flatten_json(child, path, output)
return outputThis simple helper keeps lists intact. If you need indexed paths like items.0.sku, add list handling deliberately or preview array behavior with Flatten JSON Array.
pandas json_normalize vs flattening
pandas.json_normalize() is excellent when your goal is a DataFrame. A JSON flattener is better when you need a general path map, a browser preview, a CSV-ready object, or a language-independent example before writing code.
Use pandas when the next operation is analysis. Use flattening when the next operation is export, diff, documentation, or API debugging. If the result is going to Excel, pair this page with Flatten JSON for CSV.
Common Python mistakes
- Treating
Noneas an object instead of a leaf value. - Flattening lists without deciding whether they should stay lists or become indexed paths.
- Using dot keys when the original source keys already contain dots.
- Losing numeric and boolean types by stringifying values too early.
- Writing a recursive helper before checking what output shape the downstream CSV or API expects.
Related flatten JSON tools
- JSON flattener - preview the canonical flatten and nest behavior.
- Flatten JSON in Node.js - server-side JavaScript examples.
- Flatten JSON with a delimiter - avoid path separator collisions.
- Unflatten JSON - rebuild nested objects from flat Python-style keys.
Frequently asked questions
How do I flatten JSON in Python?+−
Use a recursive helper that walks nested dicts, joins keys into a path, and emits primitive values at the leaves. Keep lists intact unless you deliberately want indexed paths.
Is pandas json_normalize the same as flattening JSON?+−
pandas json_normalize is a DataFrame-oriented flattening tool. A general JSON flattener creates path-key objects that are useful for CSV, diffs, fixtures, and API debugging.
Should Python flatten arrays by index?+−
Only when the destination expects indexed paths. For long arrays, normalize child objects into separate rows instead of creating many columns.
Related tools
- Rename KeysRename known keys or convert key casing without changing the underlying values
- Find & ReplaceFind and replace matching keys or values across JSON using broad search patterns
- FilterFilter rows, items, keys, or values by explicit conditions and keep only the matches you want
- Pick FieldsKeep only a known allowlist of fields and remove everything else
- RestructureFlexibly restructure collections by grouping, unwinding, transposing, or rearranging nested data
Read more on the blog
Advanced usage (optional)
Flatten / Nest
v1.0.0Description
Flatten / Nest
Convert between nested and flat object structures. Flatten deep objects into single-level key-value pairs, or nest flat keys back into hierarchical objects. Supports multiple key formats: delimiter-separated, camelCase, snake_case, PascalCase, and kebab-case.
Modes
Flatten
Convert nested objects into flat keys. Each nested path becomes part of the key name.
{ "user": { "name": "Alice" } } → { "user.name": "Alice" }Nest
Convert flat keys back into nested objects by splitting on the delimiter or case boundaries.
{ "user.name": "Alice" } → { "user": { "name": "Alice" } }Key Formats
Delimiter (default)
Join/split key segments with a character (default: .).
- Flatten:
user+name→user.name - Nest:
user.name→user/name
camelCase
Join/split on uppercase letter boundaries.
- Flatten:
user+address+city→userAddressCity - Nest:
userAddressCity→user/address/city
snake_case
Join/split on underscores.
- Flatten:
user+address+city→user_address_city - Nest:
user_address_city→user/address/city
PascalCase
Same as camelCase but with uppercase first letter.
- Flatten:
user+name→UserName
kebab-case
Join/split on hyphens.
- Flatten:
user+name→user-name
Configuration
| Field | Type | Default | Description |
|---|---|---|---|
| Mode | enum | flatten | flatten or nest |
| Key Format | enum | delimiter | delimiter, camelCase, snake_case, PascalCase, or kebab-case |
| Delimiter | string | . | Character(s) used to join/split key segments (only for delimiter format) |
| Max Depth | number | 0 | Maximum nesting depth to flatten (0 = unlimited) |
| Target Paths | path-picker | [] | Scope operation to specific paths only (empty = apply everywhere) |
Use Cases
API Integration
- Flatten for forms: Convert nested API responses to flat form field names
- Nest for APIs: Convert flat form data back to nested API request bodies
- Format conversion: Transform between dot-notation and camelCase conventions
Database Operations
- MongoDB flattening: Flatten nested documents for tabular export
- SQL mapping: Convert hierarchical JSON to flat column names for SQL insertion
- Schema migration: Convert between naming conventions (snake_case ↔ camelCase)
Configuration Management
- Environment variables: Flatten config objects to dot-notation for
.envfiles - Depth limiting: Flatten only the first level while preserving deep structures
Configuration
| Name | Type | Default | Description |
|---|---|---|---|
| Mode | enum | flatten | flatten: convert nested objects to flat keys. nest: convert flat keys back to nested objects. flatten nest |
| Key Format | enum | delimiter | delimiter: use a character to join/split. Others: camelCase, snake_case, PascalCase, kebab-case. delimiter camelCase snake_case PascalCase kebab-case |
| Delimiter | string | . | Character(s) used to join/split key segments (default is dot) |
| Max Depth | number | 0 | Maximum nesting depth to flatten (0 = unlimited) |
| Target Paths | path-picker | [] | Scope operation to specific paths only (empty = apply everywhere) |
Examples
Flatten or nest keys in this JSON structure and flatten nested object.1{2 "user.name": "Alice",3 "user.address.city": "NYC",4 "user.address.zip": "10001"5}API Usage
curl -X POST https://your-domain.com/api/v1/utilities/structure.flatten-nest \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"inputs":{"primary":{"user":{"name":"Alice","address":{"city":"NYC","zip":"10001"}}}},"config":{"mode":"flatten","delimiter":".","maxDepth":0,"targetPaths":[]}}'1{2 "user.name": "Alice",3 "user.address.city": "NYC",4 "user.address.zip": "10001"5}