QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Flatten Nested JSON

Flattens a nested JSON object into a flat dictionary.

  • json
  • flatten
  • nested

Code

def flatten_json(nested_json, prefix=''):
    flat_dict = {}
    for key, value in nested_json.items():
        if isinstance(value, dict):
            flat_dict.update(flatten_json(value, prefix + key + '.'))
        else:
            flat_dict[prefix + key] = value
    return flat_dict

Usage

nested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}
flatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}