Registry / data / flatten-json

flatten-json

JSON →
library0.1.14pypypi✓ verified 30d ago

flatten-json is a Python library that efficiently flattens nested JSON objects into a single-level dictionary, making them suitable for tabular formats like Pandas DataFrames or CSV export. It also provides functionality to 'unflatten' these single-level dictionaries back into nested JSON structures. The current version is 0.1.14, with a history of regular minor updates.

pip install flatten-json
INSTALL
IMPORT
SIG · FLATTEN-JSON
F
flatten-json
datapythonv0.1.14
Install
1.5s avg
Import
20ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.1.14 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.022s · 17.9MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 1.5s · import 0.018s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

flatten
✓ from flatten_json import flatten
unflatten
✓ from flatten_json import unflatten
flatten_preserve_lists
✓ from flatten_json import flatten_preserve_lists

This quickstart demonstrates the core `flatten` and `unflatten` functionalities. It also shows `flatten_preserve_lists` for scenarios where nested lists should remain lists, but their dictionary elements are still flattened. By default, `flatten` converts list items into indexed keys.

from flatten_json import flatten, unflatten # Example nested dictionary nested_dict = { "id": 1, "user": {"name": "Alice", "email": "alice@example.com"}, "orders": [ {"order_id": "A1", "items": ["apple", "banana"]}, {"order_id": "A2", "items": ["orange"]} ], "metadata": {"last_updated": "2023-10-26"} } # Flatten the dictionary flattened_dict = flatten(nested_dict) print("\nFlattened Dictionary:") print(flattened_dict) # Expected output might look like (keys sorted differently based on Python version): # { # 'id': 1, # 'user_name': 'Alice', # 'user_email': 'alice@example.com', # 'orders_0_order_id': 'A1', # 'orders_0_items_0': 'apple', # 'orders_0_items_1': 'banana', # 'orders_1_order_id': 'A2', # 'orders_1_items_0': 'orange', # 'metadata_last_updated': '2023-10-26' # } # Unflatten the dictionary unflattened_dict = unflatten(flattened_dict) print("\nUnflattened Dictionary:") print(unflattened_dict) # Flattening while preserving lists (available from v0.1.7+) from flatten_json import flatten_preserve_lists flattened_preserve_lists = flatten_preserve_lists(nested_dict) print("\nFlattened (preserving lists) Dictionary:") print(flattened_preserve_lists) # Expected output might look like: # { # 'id': 1, # 'user_name': 'Alice', # 'user_email': 'alice@example.com', # 'orders': [ # {'order_id_': 'A1', 'items_0': 'apple', 'items_1': 'banana'}, # {'order_id_': 'A2', 'items_0': 'orange'} # ], # 'metadata_last_updated': '2023-10-26' # }
Debug
Known issues
breakingVersion `0.1.13` was a broken release and was subsequently yanked from PyPI. Avoid installing or using this specific version.
fix
Use version `0.1.14` or later, or `0.1.12` or earlier.
affects: 0.1.13
gotchaThe default `flatten` function converts elements of lists into indexed keys (e.g., `list_0_item`, `list_1_item`). If you need to preserve lists as actual list structures (e.g., for compatibility with other tools or specific processing), use `flatten_preserve_lists`.
fix
For versions 0.1.7 and later, import and use `flatten_preserve_lists` instead of `flatten` if list preservation is desired. Otherwise, be aware of the indexed key convention.
affects: <0.1.7 (feature not present), all versions for default behavior
gotchaThe `unflatten` function relies on specific key patterns (e.g., `key_0_sub_key`, `key_1_sub_key`) to reconstruct nested dictionaries and lists. If your flattened data did not originate from `flatten-json` or uses different naming conventions, `unflatten` might produce unexpected results or fail to reconstruct the original structure accurately, especially for complex nested lists.
fix
Ensure that the keys in your flattened dictionary adhere to the `flatten-json` naming convention, particularly for list indices (e.g., `_0`, `_1`). Test `unflatten` thoroughly with your specific data before relying on it for critical operations.
affects: All versions with `unflatten` (0.1.5+)
deprecatedIn earlier versions (prior to 0.1.5), the primary flattening function might have been referenced directly as `flatten_json.flatten_json`. While `from flatten_json import flatten` is the idiomatic Python way to import the function, older codebases might exhibit the less conventional pattern.
fix
Update imports to `from flatten_json import flatten` and `from flatten_json import unflatten` for clarity and consistency with modern usage.
affects: <0.1.5
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'flatten_json'
The 'flatten_json' library is either not installed in the current Python environment or is incorrectly imported. The package name for installation is 'flatten_json', which also corresponds to the module name.
fix
Ensure the library is installed using `pip install flatten_json` and imported correctly as `from flatten_json import flatten` (or `import flatten_json`).
AttributeError: 'str' object has no attribute 'items'
The `flatten` function (or a similar custom flattening implementation) was called with a string as input, but it expects a dictionary-like object that has an `items()` method. This often happens if JSON data read from a file was not parsed with `json.loads()` or if an element within a list was unexpectedly a string instead of a dictionary.
fix
Ensure the input to `flatten()` is a Python dictionary. If reading from a file or API response, parse the JSON string first using `import json; data = json.loads(json_string)`. If iterating, check the type of each element before attempting to flatten.
TypeError: list indices must be integers, not str
This error occurs when attempting to access elements of a Python list using a string as an index, while lists only support integer indices. In the context of JSON flattening, this often indicates that a list was treated as a dictionary, or a key was mistakenly used to index a list instead of a dictionary.
fix
Review the data structure to distinguish between lists and dictionaries. When iterating through JSON, ensure that list elements are accessed by integer indices and dictionary elements by string keys. The `flatten_json` library handles lists by default using integer suffixes for keys (e.g., `parent_0`, `parent_1`). If implementing custom logic, ensure correct type handling.
flatten-json unflatten lists ambiguity / unflatten produces dictionary instead of list
When `flatten_json` processes a list, it generates keys with integer suffixes (e.g., `parent_0`, `parent_1`). During the `unflatten` operation, it's ambiguous whether these keys should reconstruct into a Python list `[value0, value1]` or a dictionary `{0: value0, 1: value1}`. The default `unflatten` might not always produce the desired list structure.
fix
Use `from flatten_json import unflatten_list` and call `unflatten_list(flattened_data)` when you expect lists to be reconstructed. This function includes a post-processing step to correctly identify and convert zero-indexed consecutive integer keys back into Python lists.
Upgrade
Version history
0.1.14latest on PyPI · released Oct 27, 2023
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Resources
flatten-json — pip install flatten-json · libregistry