python - Converting CSV to JSON omits last row? -


trying convert csv file json file possible while adding root node. reason, json file omits @ least last row (in cases many 4 rows) end of csv file. what's going on here?

example csv

name, id, tag john, 12345, father mary, 33456, sister beth, 56789, daughter 

desired json

{"node": "", "children": [ {"name": "john", "id": 12345, "tag": "father"}, {"name": "mary", "id": 33456, "tag": "sister"}, {"name": "beth", "id": 56789, "tag": "daughter"} ]} 

what i'm getting:

 {"node": "", "children": [     {"name": "john", "id": 12345, "tag": "father"},     {"name": "mary", "id": 33456, "tag": "sister"},     ]} 

my code:

csvfile = open('file.csv', 'r') jsonfile = open('file.json', 'w')  reader = csv.dictreader(csvfile) jsonfile.write('{"node": "", "children": [') row in reader:     json.dump(row, jsonfile)     #jsonfile.write(',\n') jsonfile.write('] }') 

p.s. know i'm adding comma on last row of json file--i'd love know how add comma after last row, that's less important.

you don't need manually construct json string. make python data structure , dump json file via json.dump():

import json  reader = csv.dictreader(csvfile) data = {"node": "", "children": list(reader)}  open('file.json', 'w') jsonfile:         json.dump(data, jsonfile) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -