0

I'm having a few problems with converting a csv file to a json file using Python. Mainly in getting it formatted the way I want, like the following:

[{'foo':'bar', 'foobar':'baz'},
{'foo':'bar', 'foobar':'baz'},
...
{'foo':'bar', 'foobar':'baz'}]

Originally I had this for my conversion:

csv_file = csv.DictReader(open(infile.csv, 'r'))
json_file = open(outfile.json, 'w')
json_file.write('[')
for row in csv_file:
    json.dump(row, json_file)
    json_file.write(',\n')
json_file.write(']')
json_file.close()

This gives me the desired look, but the problem with this is that it adds a comma at the end of the final json object, which creates an invalid json file.

I then tried loading the csv data into a list first and then dumping that:

csv_file = csv.DictReader(open(infile.csv, 'r'))
json_file = open(outfile.json, 'w')
data = []
for row in csv_file:
    data.append(row)
json.dump(data, json_file, indent=0)
json_file.close()

While this method gave me a valid format, it also gave me a file looking like this:

[
{
'foo':'bar',
'foobar':'baz'
},
{
'foo':'bar',
'foobar':'baz'
},
...
{
'foo':'bar',
'foobar':'baz'
}
]

Only problem with that is it isn't very pretty. Any suggestions on how I can get the formatting like the first example?

dselgo
  • 271
  • 3
  • 14
  • 1
    what's wrong with `json.dump` ? – Jean-François Fabre Mar 23 '17 at 20:36
  • nothing is, the problem is that I'm unable to use it get my json file to look how I want. If you look above I used `json.dump` in both of my examples, but I'm having trouble getting it the way I want. Ideally if I could read the csv line by line like the first example and get rid of the last comma I would be set. – dselgo Mar 23 '17 at 20:44
  • 1
    in that case, issue the comma line first (with a flag preventing it at first iteration). That's pretty basic. – Jean-François Fabre Mar 23 '17 at 20:48
  • ...wow I feel dumb that I didn't think of that now. It's been a long day lol. Thanks for the suggestion! – dselgo Mar 23 '17 at 20:49
  • you're welcome. nice if it solves your problem. I don't want to answer something like that because I feel that it wouldn't help too many other people, but at least you get your solution. – Jean-François Fabre Mar 23 '17 at 20:51
  • yup, worked perfectly. Simple solutions to simple problems. Thanks again! – dselgo Mar 23 '17 at 20:57

0 Answers0