'How to make csv rows into separate JSON files that contain objects?
I am currently trying to turn my csv rows into JSON files with objects opposed to arrays. My issue is that when running my code, I am getting files with arrays instead of objects.
import csv
import json
JSON_ENTRIES_THRESHOLD = 1 # modify to whatever you see suitable
def write_json(json_object, filename):
with open(filename, 'w', encoding='utf-8') as jsonf:
json.dump(json_object, jsonf) # note the usage of .dump directly to a file
descriptor
def csv_to_json(csvFilePath, jsonFilePath):
jsonObject = []
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
filename_index = 0
for row in csvReader:
jsonObject.append(row)
if len(jsonObject) >= JSON_ENTRIES_THRESHOLD:
# if we reached the treshold, write out
write_json(jsonObject, f"jsonFilePath-{filename_index}.json")
filename_index += 1
jsonObject = []
# Finally, write out the remainder
write_json(jsonObject, f"jsonFilePath-{filename_index}.json")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
