Skip to content

Instantly share code, notes, and snippets.

@chreke
Last active August 29, 2015 14:07
Show Gist options
  • Save chreke/e31f09a8c8b8d0efb801 to your computer and use it in GitHub Desktop.
Save chreke/e31f09a8c8b8d0efb801 to your computer and use it in GitHub Desktop.
JSON to CSV
#!/usr/bin/env python
# Reads JSON from a file or STDIN and outputs CSV to STDOUT.
import fileinput
import json
import sys
import csv
jsonstr = ''
for line in fileinput.input():
jsonstr += line
dicts = json.loads(jsonstr)
header = sorted(set(k for d in dicts for (k, v) in d.items()))
with sys.stdout as out:
dw = csv.DictWriter(out, header)
dw.writeheader()
for d in dicts:
dw.writerow(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment