Created
January 24, 2017 22:58
-
-
Save aryzhov/067ecc12d39715217d787896a34915c6 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was created to aid my answer to the stackoverflow question: http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys