Skip to content

Instantly share code, notes, and snippets.

@aryzhov aryzhov/
Created Jan 24, 2017

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:
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))
json2 = dict()
json1[k1] = json2
json1 = json2
if type(json1) == dict:
v = json.pop(k)
json1[key_parts[-1]] = v

This comment has been minimized.

Copy link
Owner Author

commented Jan 24, 2017

This was created to aid my answer to the stackoverflow question:

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.