Flatten JSON Objects

0.1.14 · active · verified Fri Apr 10

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.

Warnings

Install

Imports

Quickstart

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'
# }

view raw JSON →