Skip to content

Instantly share code, notes, and snippets.

@omarish
Created November 11, 2010 00:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omarish/671791 to your computer and use it in GitHub Desktop.
Save omarish/671791 to your computer and use it in GitHub Desktop.
Easily convert a CSV file to JSON.
#!/usr/bin/env python
import csv
try: import simplejson as json
except: import json
from optparse import OptionParser
def main():
usage = "usage: csv2json: %prog [options] arg"
parser = OptionParser()
parser.add_option("-i","--input",dest="input",help="input csv file")
parser.add_option("-o","--output", dest="output", help="output json file")
(options, args) = parser.parse_args()
input = open( options.input, 'rU' )
output = open( options.output, 'w' )
reader = csv.DictReader( input, fieldnames = input.readline().split(",") )
output.write( json.dumps( [ row for row in reader ] ) )
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment