Python functions for flattening a JSON object to a single dictionary of pairs, and unflattening that dictionary back to a JSON object
Low maintenance activity. Last release over 2 years ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install json-flattenjson-flatten
Python functions for flattening a JSON object to a single dictionary of pairs, and unflattening that dictionary back to a JSON object.
This can be useful if you need to represent a JSON object using a regular HTML form or transmit it as a set of query string parameters.
For example:
>>> import json_flatten
>>> json_flatten.flatten({"foo": {"bar": [1, True, None]}})
{'foo.bar.[0]$int': '1', 'foo.bar.[1]$bool': 'True', 'foo.bar.[2]$none': 'None'}
>>> json_flatten.unflatten(_)
{'foo': {'bar': [1, True, None]}}
The top-level object passed to flatten() must be a dictionary.
JSON flattening format
Basic principles
- Keys are constructed using dot notation to represent nesting.
- Type information is preserved using
$typesuffixes. - List indices are represented using
[index]notation. - Empty objects and lists have special representations.
Nested objects
For nested objects, keys are constructed by joining the nested keys with dots.
Example:
{
"user": {
"name": "John",
"age": 30
}
}
Flattened:
user.name=John
user.age$int=30
Lists
List items are represented using [index] notation.
Example:
{
"fruits": [
"apple",
"banana",
"cherry"
]
}
Flattened:
fruits.[0]=apple
fruits.[1]=banana
fruits.[2]=cherry
Nested lists
For nested lists, the index notation is repeated.