Skip to content

Instantly share code, notes, and snippets.

@jvangael
Created January 24, 2013 09:45
Show Gist options
  • Save jvangael/4619288 to your computer and use it in GitHub Desktop.
Save jvangael/4619288 to your computer and use it in GitHub Desktop.
Little utility to transform a file with lines of json into a csv. The utility accepts a list of field names it will look for in the json and turn them into columns of the csv. This script relies on docopt and unicodecsv packages.
#!/usr/bin/env python
"""Reads json lines from stdin and write csv to stdout.
Usage:
json2csv.py -f <field>...
json2csv.py -h | --help
json2csv.py --version
Options:
-h --help Show this screen.
--version Show version.
-f --fields Specify headers of the csv file.
"""
from unicodecsv import DictWriter
from docopt import docopt
import json
import sys
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1')
csv_wrt = DictWriter(sys.stdout, extrasaction="ignore", fieldnames=arguments['<field>'])
csv_wrt.writeheader()
for line in sys.stdin:
datum = json.loads(line)
csv_wrt.writerow(datum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment