Created
March 19, 2014 16:16
-
-
Save mturilin/9645291 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
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