【发布时间】:2020-10-28 19:36:07
【问题描述】:
请帮帮我!!我还在学习数据结构和 我正在尝试转换此 CSV 文件
key,a,b,c,d,e
key_01,apple,100,200,doll,elephant
key_02,apple,100,200,doll,elephant
key_03,apple,100,200,doll,elephant
转为 Json 格式。我试过这个脚本
import csv
import json
csvFilePath = 'my.csv'
jsonFilePath = 'my.json'
def make_json(csvFilePath, jsonFilePath):
data = {}
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for rows in csvReader:
key = rows["key"]
data[key] = rows
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
make_json(csvFilePath, jsonFilePath)
但输出中有关键行
{
"key_01": {
"key": "01",
"a": "apple",
"y": "100.0",
"c": "cow",
"d": "doll",
"e": "elephant"
},
"key_02": {
"key": "02",
"a": "apple",
"y": "100.0",
"c": "cow",
"d": "doll",
"e": "elephant"
},
}
我希望我的最终输出看起来像这样。有什么办法可以做到这一点?请帮帮我。
{
"key_01": {
"a": "apple",
"y": "100.0",
"c": "cow",
"d": "doll",
"e": "elephant"
},
"key_02": {
"a": "apple",
"y": "100.0",
"c": "cow",
"d": "doll",
"e": "elephant"
},
"key_03": {
"a": "apple",
"y": "100.0",
"c": "cow",
"d": "doll",
"e": "elephant"
},
【问题讨论】:
标签: python json csv dictionary data-structures