我正在尝试将 csv 格式转换为 JSON,我用谷歌搜索我没有得到修改它以获得所需格式的正确方法。
这是我在 python 中的代码:
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
#reading csv (encoding is important)
with open(csvFilePath, encoding='utf-8') as csvf:
#csv library function
csvReader = csv.DictReader(csvf)
#convert each csv row into python dictionary
for column in csvReader:
#add this python dictionary to json array
jsonArray.append(column)
#convertion
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath='example.csv'
jsonFilePath='output.json'
csv_to_json(csvFilePath, jsonFilePath)
这是我的 csv 文件格式:
我实际的 JSON 输出:
[
{
"Area": "IT",
"Employee": "Carl",
},
{
"Area": "IT",
"Employee": "Walter",
},
{
"Area": "Financial Resources",
"Employee": "Jennifer",
}
]
我想要的 JSON 输出:
[
{
"Area": "IT",
"Employee": ["Carl","Walter"],
},
{
"Area": "Financial Resources",
"Employee": ["Jennifer"],
}
]
提前致谢!
最佳答案
这样的事情应该可行。
def csv_to_json(csvFilePath, jsonFilePath):
areas = {}
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for column in csvReader:
area, employee = column["Area"], column["Employee"] # split values
if area in areas: # add all keys and values to one dictionary
areas[area].append(employee)
else:
areas[area] = [employee]
# convert dictionary to desired output format.
jsonArray = [{"Area": k, "Employee": v} for k,v in areas.items()]
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
关于python - CSV 到 JSON 转换器(按相同键值分组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73042986/