Created
August 2, 2019 13:44
-
-
Save ramnes/e53a51561fe4bf51e8e959a0576e44fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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