Skip to content

Instantly share code, notes, and snippets.

@mturilin
Created March 19, 2014 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mturilin/9645291 to your computer and use it in GitHub Desktop.
Save mturilin/9645291 to your computer and use it in GitHub Desktop.
import json
import unicodecsv as csv
import sys
def recursive_keys(row):
keys = set()
for k in row.keys():
if isinstance(row[k], dict):
for subkey in recursive_keys(row[k]):
keys.add("%s.%s" % (k, subkey))
else:
keys.add(k)
return keys
def recursive_get(d, key):
key_list = key.split('.')
val = d
try:
for key_item in key_list:
val = val[key_item]
except KeyError:
return None
return val
myjson = json.loads(open(sys.argv[1]).read())
try:
relative_key = sys.argv[2]
myjson = recursive_get(myjson, relative_key)
except:
print "No relative keys"
keys = set()
for row in myjson:
keys.update(recursive_keys(row))
mycsv = csv.DictWriter(sys.stdout, fieldnames=keys, quoting=csv.QUOTE_MINIMAL)
mycsv.writeheader()
for row in myjson:
converted_row = {k: recursive_get(row, k) for k in keys}
mycsv.writerow(converted_row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment