0

Good afternoon sirs

I already know how to convert a csv file to json, however I am now unable to get each csv line saved in a different json.

Example:

Row 1: Json1.json

Row 2: Json2.json

The name of each file would be the fieldName of each row

Could someone give me a light on this?

The code follows:

import csv  
import json  

# Open the CSV  
f = open( '/path/to/filename.csv', 'rU' )  
# Change each fieldname to the appropriate field name. I know, so     difficult.  
reader = csv.DictReader( f, fieldnames = (    "fieldname0","fieldname1","fieldname2","fieldname3" ))  
# Parse the CSV into JSON  
out = json.dumps( [ row for row in reader ] )  
print "JSON parsed!"  
# Save the JSON  
f = open( '/path/to/parsed.json', 'w')  
f.write(out)  
print "JSON saved!"  
1
  • 1
    [ row for row in reader ] is list(reader) (do not overcomplicate your code). Commented Jan 20, 2017 at 19:48

1 Answer 1

4

make a new json for each row

for idx, row in enumerate(reader,1):
   fout = open('Json'+str(idx)+'.json','w')
   fout.write(json.dumps(row))
   fout.close()
Sign up to request clarification or add additional context in comments.

1 Comment

please close your file explicitly or use a with block. and use format to generate filename. Otherwise nice.

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.