Skip to content

Instantly share code, notes, and snippets.

@aryzhov
Created January 24, 2017 22:58
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save aryzhov/067ecc12d39715217d787896a34915c6 to your computer and use it in GitHub Desktop.
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
Copy link
Author

aryzhov 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