我正在尝试将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"],
}
]
提前感谢您!
jsonArray = [{"Area": k, "Employee": v, "anotherfield": a,} for k,v,a in areas.items()]
但是这种写法是不被允许的。 - Mauricio ReyesjsonArray = [{"Area": k, "Employee": v, "anotherfield": "somevalue"} for k, v in areas.items()]
- Alexander