Skip to content

Instantly share code, notes, and snippets.

@higarmi
higarmi / Flatten JSON or a nested dictionary
Created September 26, 2013 01:49
This python recursive function flattens a JSON file or a dictionary with nested lists and/or dictionaries. The output is a flattened dictionary that use dot-chained names for keys, based on the dictionary structure. This allows for reconstructing the JSON structure or converting it to other formats without loosing any structural information.
"""
example: The following JSON document:
{"maps":[{"id1":"blabla","iscategorical1":"0", "perro":[{"dog1": "1", "dog2": "2"}]},{"id2":"blabla","iscategorical2":"0"}],
"masks":{"id":"valore"},
"om_points":"value",
"parameters":{"id":"valore"}}
will have the following output:
{'masks.id': 'valore', 'maps.iscategorical2': '0', 'om_points': 'value', 'maps.iscategorical1': '0',
'maps.id1': 'blabla', 'parameters.id': 'valore', 'maps.perro.dog2': '2', 'maps.perro.dog1': '1', 'maps.id2': 'blabla'}