user413734 user413734 - 27 days ago 8
Python Question

CSV file to JSON file in Python

I have read quite a lot of posts here and elsewhere, but I can't seem to find the solution. And I do not want to convert it online.

I would like to convert a CSV file to a JSON file (no nesting, even though I might need it in the future) with this code I found here:

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


Awesome, simple, and it works. But I do not get a .csv file, but a text output that if I copy and paste, is one long line.

I would need a .json that is readable and ideally saved to a .json file.
Is this possible?

Answer

To get more readable JSON, try the indent argument in dumps():

print json.dumps(..., indent=4)

However - to look more like the original CSV file, what you probably want is to encode each line separately, and then join them all up using the JSON array syntax:

out = "[\n\t" + ",\n\t".join([json.dumps(row) for row in reader]) + "\n]"

That should give you something like:

[
    {"id": 1, "name": "foo", ...},
    {"id": 2, "name": "bar", ...},
    ...
]

If you need help writing the result to a file, try this tutorial.

Comments