Skip to content

Instantly share code, notes, and snippets.

@ftao
Created June 17, 2015 02:22
Show Gist options
  • Save ftao/101c8cecd8671bc83c36 to your computer and use it in GitHub Desktop.
Save ftao/101c8cecd8671bc83c36 to your computer and use it in GitHub Desktop.
flatten json
import sys
import json
def flatten(data):
for key, value in data.iteritems():
if type(value) is dict:
for k,v in flatten(value):
yield (key + '.' + k, v)
else:
yield (key, value.encode("utf-8"))
def convert(infile, outfile):
with open(infile, 'r') as fp:
data = json.load(fp)
with open(outfile, 'w') as outfp:
json.dump(dict(flatten(data)), outfp, sort_keys=True, indent=2, ensure_ascii=False)
if __name__ == "__main__":
infile, outfile = sys.argv[1], sys.argv[2]
convert(infile, outfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment