Johntron

Python, PHP, Zend, Django, Mobile, and Linux web development guru



CSV-to-JSON

Here is a very simple script to convert CSV to JSON using Python. Writing a script like this is very trivial. You only need it once in a while, and sometimes you forget names of things. Hopefully this will save someone a few minutes of coding. csv2json.py requires Python 2.6 or greater. If you have any questions, please contact me.

import csv
import json

f = open( 'sample.csv', 'r' )
reader = csv.DictReader( f, fieldnames = ( "id","name","lat","lng" ) )
out = json.dumps( [ row for row in reader ] )
print out

Download csv2json.tar.gz

If you find this page helpful, check out some of my other posts on Johntron.com or consider leaving a comment.

  • http://www.focustheweb.com giovanni

    Hi,
    thanks for your code!
    http://www.focustheweb.com/2010/08/a-simple-scr…

    giovanni

  • Jacob

    Thx! Really helpful script and way better than the onlinen csv to json converters which don’t like big file sizes.

    • http://www.johntron.com Johntron

      You’re welcome! Thanks for the feedback :)