I'm reading in a CSV file and output-ing a JSON file which is then processed by another application. Some of the information needed by the downstream app is not present in the CSV file and needs to be obtained programmatically from another source. Is there a way to edit/insert fields into the CSV data prior to output-ing the JSON data? I've been glassing over the Python CSV module docs and noticed the for row in reader:
example. I can iterate over the known fields and then insert the new ones to build a new_row
variable. I can dump new_row
to the JSON file but the field names given to the original reader
don't coming along for the ride so I end up with a pretty crazy new_row
variable that doesn't feel like I'm saving anything. Thoughts?
#!/usr/bin/python
import urllib
import json
import sys
import csv
fieldnames = ("first_name", "last_name","phone")
reader = csv.DictReader(csvfile, fieldnames)
all_lines = list(reader)
jsonfile.write ('{"people":[')
for row in all_lines:
jsonfile.write('{"person":')
#address = my_get_address (...)
new_row = ["first_name", row['first_name'], "last_name", row['last_name'], "phone", row['phone'], 'address', '123 anystreet']
json.dump(new_row, jsonfile)
jsonfile.write('}')
# comma + newline for every person excep the last
if row != all_lines[-1]:
jsonfile.write (',\n')
jsonfile.write (']}')
JSON output:
{
"people" : [
{
"person" : [
"first_name",
"joe",
"last_name",
"smith",
"phone",
"999-555-1212",
"address",
"123 anystreet"
]
},
{
"person" : [
"first_name",
"mary",
"last_name",
"jones",
"phone",
"888-555-1212",
"address",
"123 anystreet"
]
}
]
}
json
module build the whole JSON string instead of manually concentrate things.data
while populating the the it add extra columns/ editing it you want. Once that done you can simply dump the data to a json file as second step.(geeksforgeeks.org/convert-csv-to-json-using-python)"mary", "jones", "888-555-1212"