i have a csv with columns,
Column_one | Column_two
1 | apple
2 | orange
...
import csv
import json
rows=[]
dataRow = {}
with open('input.csv', mode='r') as csvFile:
csvReader = csv.DictReader(csvFile)
for row in csvReader:
rows.append('"{0}":"{1}"'.format(row["Column_one"], row["Column_two"]))
with open('output.json', 'w') as output_file:
output_file.write(json.dumps(rows))
I am formatting the output so that i can get output file as such
{"1" : "apple"}
{"2" : "orange"}
but i get results below , i tried escaping the double quotes with add backlash in front of double quotes, but that just gives me double backlash infront of quotes
{\"1\": \"apple:\"},
{\"2\" : \"orange\"}
CodePudding user response:
If you want individual objects on each line, then you cannot dump an entire list.
Separate your concerns - parse the file into dict rows, then write a new one.
import csv
def csv2dict(filename):
with open(filename) as f:
reader = csv.DictReader(f)
h1, h2 = reader.fieldnames[:2]
for r in reader:
yield {r[h1]:r[h2]}
# Or to get all column headers to their values
# yield {f:r[f] for f in reader.fieldnames}
import json
with open('output.json', 'w') as f:
for d in csv2dict('input.csv'):
json.dump(d, f)
f.write('\n')
Outputs
{"1": "apple"}
{"2": "orange"}
Note: You don't really need the DictReader; a regular csv.Reader
has index access to the columns.
CodePudding user response:
You could try like this
import csv
import json
rows=[]
dataRow = {}
with open('input.csv', mode='r') as csvFile:
csvReader = csv.DictReader(csvFile)
for row in csvReader:
rows.append(dict(row["Column_one"]: row["Column_two"]))
with open('output.json', 'w') as output_file:
output_file.write(json.dumps(rows, indent=4))
CodePudding user response:
You are manually creating a string that looks like JSON, and then encoding it again with json.dumps
, so you get a JSONified version of a JSON string.
You can write JSON manually if you want:
>>> print('{{"{}":"{}"}}'.format('1', 'apple'))
{"1":"apple"}
or (preferably) you can using the json module to encode a dictionary as JSON:
>>> print(json.dumps({'1':'apple'}))
{"1": "apple"}
But if you do both, you get a JSON representation of an already JSONified string, which looks like this:
>>> print(json.dumps('{{"{}":"{}"}}'.format('1', 'apple')))
"{\"1\":\"apple\"}"