Skip to content

Instantly share code, notes, and snippets.

@ramnes
Created August 2, 2019 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramnes/e53a51561fe4bf51e8e959a0576e44fa to your computer and use it in GitHub Desktop.
Save ramnes/e53a51561fe4bf51e8e959a0576e44fa to your computer and use it in GitHub Desktop.
import json
def flatten(o):
"""Flatten dicts and lists, recursively, JSON-style
It's a generator that yields key-value pairs.
Example:
>>> dict(flatten({"a": [{"b": 1}, [2, 3], 4, {"c.d": 5, True: 6}]}))
{'.a[0].b': 1,
'.a[1][0]': 2,
'.a[1][1]': 3,
'.a[2]': 4},
'.a[3]["c.d"]': 5,
'.a[3][true]': 6}
"""
if isinstance(o, dict):
for key, value in o.items():
if isinstance(key, str) and "." in key:
key = '["{}"]'.format(key)
elif isinstance(key, str):
key = ".{}".format(key)
else:
key = '[{}]'.format(json.dumps(key))
for subkey, subvalue in flatten(value):
yield key + subkey, subvalue
elif isinstance(o, list):
for index, value in enumerate(o):
for subkey, subvalue in flatten(value):
yield "[{}]".format(index) + subkey, subvalue
else:
yield "", o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment