JSON Flatten and Unflatten Utilities
json-flatten is a Python library providing functions to convert a nested JSON object into a single-level dictionary of key-value pairs, and to reconstruct the original JSON object from that flattened representation. It's particularly useful for scenarios like converting JSON for HTML forms or query string parameters. The library is actively maintained, with releases typically addressing bug fixes and minor enhancements. The latest version is 0.3.1.
Warnings
- breaking Starting from version 0.3, the `flatten()` function now explicitly checks if the input object is a dictionary. If a non-dictionary object (e.g., a list or a string) is passed, it will raise a `TypeError`.
- breaking Version 0.2 introduced a change in the serialization format used for array keys. This update correctly handles dictionaries where keys are strings containing only digits. This means data flattened with versions prior to 0.2 might not unflatten correctly with 0.2 and later, or vice-versa, if such array keys are present.
- gotcha The library uses a specific and detailed format for flattened keys, especially for array elements (e.g., `parent.array.[index]$type=value`) and includes type hints for round-tripping complex types like `None`, `True`/`False`, `int`, `float`, and `str`. While this ensures accurate unflattening, it differs from simpler flattening schemes and requires careful consideration if manually manipulating keys or integrating with other flattening tools.
Install
-
pip install json-flatten
Imports
- flatten
from json_flatten import flatten
- unflatten
from json_flatten import unflatten
Quickstart
from json_flatten import flatten, unflatten
original_json = {
"name": "Alice",
"details": {
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"hobbies": ["reading", "coding", {"sport": "swimming"}]
},
"active": True
}
# Flatten the JSON object
flattened_data = flatten(original_json)
print("Flattened Data:", flattened_data)
# Expected output for flattened_data might look like:
# {
# 'name': 'Alice',
# 'details.age': 30,
# 'details.address.street': '123 Main St',
# 'details.address.city': 'Anytown',
# 'details.hobbies.[0]$str': 'reading',
# 'details.hobbies.[1]$str': 'coding',
# 'details.hobbies.[2].sport': 'swimming',
# 'active': True
# }
# Unflatten the data back to its original structure
unflattened_json = unflatten(flattened_data)
print("Unflattened Data:", unflattened_json)
# Verify round-trip (optional)
assert original_json == unflattened_json