I would like to covert a CSV to a set of JSON objects with Python, formatted in rows.
I tried this script below, put together from a couple SO answers, but this formats this way:
{
key:'value'
},
{
key:'value'
} // etc
I would like to format this as:
{ key, 'value'},
{ key, 'value'}, // etc
I tried a few ways suggested here to insert a newline, but none worked so far.
script below:
import sys, getopt
import csv
import json
CSV_PATH = 'path/file.csv'
JSON_PATH = 'path/demo.json'
csv_file = csv.DictReader(open(CSV_PATH, 'r'))
json_list = []
for row in csv_file:
json_list.append(row )
file(JSON_PATH, 'w').write(json.dumps(json_list, indent=4, separators=(' ,') ))
my csv is straightforward:
SUM_F SUM_I SUM_P SUM_PI SUM_Bt SUM_BI SUM_M SUM_MI Year Month
15 3963 14 993 0 91 1 2879 2009 1
etc..
EDIT: I received this suggestion in the comments of another post:
for x in json_list: print json.dumps(x)
this will print the format I am looking for, but I have not yet figured out how to write this to a json file.
Alex Hall :
import csv\nimport json\n\nCSV_PATH = 'file.csv'\nJSON_PATH = 'demo.json'\n\nwith open(CSV_PATH, 'r') as csv_file:\n reader = csv.DictReader(csv_file)\n with open(JSON_PATH, 'w') as json_file:\n for row in reader:\n json_file.write(json.dumps(row) + '\\n')\n\n\nstr(row) gives the wrong kind of quotes, don't use it. You won't be able to read the file with json.",
2017-04-24T20:29:35