python3从csv文件中读取数据并将其转换为json

时间:2017-11-10 10:04:07

标签: json python-3.x csv

这是我的代码隐藏json到csv。

import csv
import json
with open('Documents/SampleCSVStory.csv', 'r') as f:
    reader = csv.reader(f, delimiter=';')
    data_list = list()
    for row in reader:
        data_list.append(row)
data = [dict(zip(data_list[0],row)) for row in data_list]
data.pop(0)
s = json.dumps(data)
print (s)

但输出就像这样

[{"Id,Name,Description": "1,User 1,Python Developer"}

我的期望是

[{"Id:"1",Name:"User 1",Description:"Python Developer"}

任何人都可以帮助我。?

1 个答案:

答案 0 :(得分:0)

import csv
import json

with open('Documents/SampleCSVStory.csv', 'r') as f:
    reader = csv.DictReader(f, delimiter=';')
json.dumps([row for row in reader])