2

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked, now I need to find out how to strucre the data in csv to get a nested json out of it. Thanks again
1

If you want a more readable format of the JSON file, use it like this:

json.dump(output_value, open('filename','w'), indent=4, sort_keys=False)

Comments

1

Here's a full script. This script uses the comma-separated values of the first line as the keys for the JSON output. The output JSON file will be automatically created or overwritten using the same file name as the input CSV file name just with the .csv file extension replaced with .json.

Example CSV file:

id,longitude,latitude
1,32.774,-124.401
2,32.748,-124.424
4,32.800,-124.427
5,32.771,-124.433

Python script:

csvfile = open('sample.csv', 'r')
jsonfile = open('sample.csv'.replace('.csv', '.json'), 'w')

jsonfile.write('{"' + 'sample.csv'.replace('.csv', '') + '": [\n') # Write JSON parent of data list
fieldnames = csvfile.readline().replace('\n','').split(',')        # Get fieldnames from first line of csv
num_lines = sum(1 for line in open('sample.csv')) - 1              # Count total lines in csv minus header row

reader = csv.DictReader(csvfile, fieldnames)
i = 0
for row in reader:
  i += 1
  json.dump(row, jsonfile)
  if i < num_lines:
    jsonfile.write(',')
  jsonfile.write('\n')
jsonfile.write(']}')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.