Created
January 24, 2013 09:45
-
-
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.
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 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