Skip to content

Instantly share code, notes, and snippets.

@aryzhov aryzhov/json_flat.py
Created Jan 24, 2017

Embed
What would you like to do?
def flatten_json(json):
if type(json) == dict:
for k, v in list(json.items()):
if type(v) == dict:
flatten_json(v)
json.pop(k)
for k2, v2 in v.items():
json[k+"."+k2] = v2
def unflatten_json(json):
if type(json) == dict:
for k in sorted(json.keys(), reverse=True):
if "." in k:
key_parts = k.split(".")
json1 = json
for i in range(0, len(key_parts)-1):
k1 = key_parts[i]
if k1 in json1:
json1 = json1[k1]
if type(json1) != dict:
conflicting_key = ".".join(key_parts[0:i+1])
raise Exception('Key "{}" conflicts with key "{}"'.format(
k, conflicting_key))
else:
json2 = dict()
json1[k1] = json2
json1 = json2
if type(json1) == dict:
v = json.pop(k)
json1[key_parts[-1]] = v
@aryzhov

This comment has been minimized.

Copy link
Owner Author

commented Jan 24, 2017

This was created to aid my answer to the stackoverflow question: http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.