Skip to content

Instantly share code, notes, and snippets.

@poundifdef
Created September 22, 2023 19:29
Show Gist options
  • Save poundifdef/cbf020f52c37c018669372feb525ed14 to your computer and use it in GitHub Desktop.
Save poundifdef/cbf020f52c37c018669372feb525ed14 to your computer and use it in GitHub Desktop.
Flatten JSON with Arrays
import json
def parse(obj, path = None, use_indices = False):
if path is None:
path = []
if isinstance(obj, list):
if use_indices:
return [p for i, item in enumerate(obj) for p in parse(item, path + [i], use_indices)]
return [p for i in obj for p in parse(i, path, use_indices) ]
if isinstance(obj, dict):
return cross_product([parse(v, path + [k], use_indices) for k, v in obj.items()])
return [{tuple(path): obj}]
def cross_product(dicts):
if len(dicts) == 0:
return [{}]
return [ {**lhs, **rhs} for lhs in dicts[0] for rhs in cross_product(dicts[1:])]
def to_json(j):
rc = []
for item in j:
converted = {}
for k,v in item.items():
converted['.'.join(k)] = v
rc.append(converted)
if __name__=='__main__':
j = parse(data)
print(to_json(j))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment