I have a .json file that contains objects that look like this:
[
{
"a": "0.038",
"b": "1",
"c": "0"
},
{
"a": "0.040",
"b": "1",
"c": "0"
},
...
]
And I have a .csv file that looks like this:
d e f
0.00 0.00 0.00
0.02 -0.08 -0.08
0.04 -0.32 -0.32
...
I would like to modify the .json file to add the new key/value pairs from the .csv file, but I'm not looking to just tack the new items at the end of the file, but rather a row from the .csv is added to the end of each element. So the new .json would look like this:
[
{
"a": "0.038",
"b": "1",
"c": "0",
"d": "0.00",
"e": "0.00",
"f": "0.00"
},
{
"a": "0.040",
"b": "1",
"c": "0",
"d": "0.02",
"e": "-0.08",
"f": "-0.08""
},
...
]
I have tried different ways (like using append() or update()), but they either add the .csv data to the complete end of the .json file or try to add the entire .csv data to the end of the first element in the .json. In my mind, what I need to do is, create a dictionary from the json object, load the csv data into a dictionary as well, loop through each json element and then add a row from the csv data into that, creating a new json object. But I'm not getting the output I want, or I run into an issue where I can't append to the dict. Here's my existing code:
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
with open("existing.json") as json_file:
data = json.load(json_file)
json_file.close() # Close the JSON file
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
for item in data:
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
item.update(row)
#convert python jsonArray to JSON string and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(data, indent = 4)
jsonf.write(jsonString)
#decide the 2 file paths according to your file system
csvFilePath = r'C:\Users\\Downloads\filename.csv'
jsonFilePath = r'C:\Users\\Desktop\filename.json'
csv_to_json(csvFilePath, jsonFilePath)