{"id":2512,"library":"flatten-json","title":"Flatten JSON Objects","description":"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.","status":"active","version":"0.1.14","language":"python","source_language":"en","source_url":"https://github.com/amirziai/flatten","tags":["json","flatten","unflatten","data transformation","dictionary","nested"],"install":[{"cmd":"pip install flatten-json","lang":"bash","label":"Install latest version"}],"dependencies":[],"imports":[{"symbol":"flatten","correct":"from flatten_json import flatten"},{"symbol":"unflatten","correct":"from flatten_json import unflatten"},{"symbol":"flatten_preserve_lists","correct":"from flatten_json import flatten_preserve_lists"}],"quickstart":{"code":"from flatten_json import flatten, unflatten\n\n# Example nested dictionary\nnested_dict = {\n    \"id\": 1,\n    \"user\": {\"name\": \"Alice\", \"email\": \"alice@example.com\"},\n    \"orders\": [\n        {\"order_id\": \"A1\", \"items\": [\"apple\", \"banana\"]},\n        {\"order_id\": \"A2\", \"items\": [\"orange\"]}\n    ],\n    \"metadata\": {\"last_updated\": \"2023-10-26\"}\n}\n\n# Flatten the dictionary\nflattened_dict = flatten(nested_dict)\nprint(\"\\nFlattened Dictionary:\")\nprint(flattened_dict)\n# Expected output might look like (keys sorted differently based on Python version):\n# {\n#  'id': 1,\n#  'user_name': 'Alice',\n#  'user_email': 'alice@example.com',\n#  'orders_0_order_id': 'A1',\n#  'orders_0_items_0': 'apple',\n#  'orders_0_items_1': 'banana',\n#  'orders_1_order_id': 'A2',\n#  'orders_1_items_0': 'orange',\n#  'metadata_last_updated': '2023-10-26'\n# }\n\n# Unflatten the dictionary\nunflattened_dict = unflatten(flattened_dict)\nprint(\"\\nUnflattened Dictionary:\")\nprint(unflattened_dict)\n\n# Flattening while preserving lists (available from v0.1.7+)\nfrom flatten_json import flatten_preserve_lists\nflattened_preserve_lists = flatten_preserve_lists(nested_dict)\nprint(\"\\nFlattened (preserving lists) Dictionary:\")\nprint(flattened_preserve_lists)\n# Expected output might look like:\n# {\n#  'id': 1,\n#  'user_name': 'Alice',\n#  'user_email': 'alice@example.com',\n#  'orders': [\n#   {'order_id_': 'A1', 'items_0': 'apple', 'items_1': 'banana'},\n#   {'order_id_': 'A2', 'items_0': 'orange'}\n#  ],\n#  'metadata_last_updated': '2023-10-26'\n# }","lang":"python","description":"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."},"warnings":[{"fix":"Use version `0.1.14` or later, or `0.1.12` or earlier.","message":"Version `0.1.13` was a broken release and was subsequently yanked from PyPI. Avoid installing or using this specific version.","severity":"breaking","affected_versions":"0.1.13"},{"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.","message":"The 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`.","severity":"gotcha","affected_versions":"<0.1.7 (feature not present), all versions for default behavior"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":"All versions with `unflatten` (0.1.5+)"},{"fix":"Update imports to `from flatten_json import flatten` and `from flatten_json import unflatten` for clarity and consistency with modern usage.","message":"In 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.","severity":"deprecated","affected_versions":"<0.1.5"}],"env_vars":null,"search_vec":"'0.1.14':55 'also':36 'back':46 'csv':33 'current':52 'data':66 'datafram':31 'dictionari':22,45,68 'effici':12 'export':34 'flatten':1,5,13,64 'flatten-json':4 'format':28 'function':38 'histori':58 'json':2,6,15,49,63 'level':21,44 'librari':10 'like':29 'make':23 'minor':61 'nest':14,48,69 'object':3,16 'panda':30 'provid':37 'python':9 'regular':60 'singl':20,43 'single-level':19,42 'structur':50 'suitabl':25 'tabular':27 'transform':67 'unflatten':40,65 'updat':62 'version':53","created_at":"2026-04-11T01:31:15.262576+00:00","updated_at":"2026-04-16T15:08:58.583190+00:00","problems":[{"fix":"Ensure the library is installed using `pip install flatten_json` and imported correctly as `from flatten_json import flatten` (or `import flatten_json`).","cause":"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.","error":"ModuleNotFoundError: No module named 'flatten_json'"},{"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.","cause":"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.","error":"AttributeError: 'str' object has no attribute 'items'"},{"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.","cause":"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.","error":"TypeError: list indices must be integers, not str"},{"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.","cause":"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.","error":"flatten-json unflatten lists ambiguity / unflatten produces dictionary instead of list"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.1.14","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/amirziai/flatten","docs":null,"changelog":null,"pypi":"https://pypi.org/project/flatten-json/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["data","serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-28","next_check":"2026-07-28","install_tag":null}}