JSON Flatten and Unflatten Utilities

0.3.1 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This example demonstrates how to flatten a nested dictionary (representing a JSON object) into a flat dictionary using `flatten()`, and then restore it to its original nested structure using `unflatten()`.

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

view raw JSON →