Last active
August 29, 2015 14:07
-
-
Save chreke/e31f09a8c8b8d0efb801 to your computer and use it in GitHub Desktop.
JSON to CSV
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
#!/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