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?