-
-
Save dschaehi/be676cdbb288c3399eee08f2342f9daa to your computer and use it in GitHub Desktop.
This file contains 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