如何在Python中将CSV转换为JSON?

18

我刚接触编程,学了大约3/4周的Python,这是其中的一个作业。

输入

A, B, C, D
1, 2, 3, 4
5, 6, 7, 8

输出

{{A:"1", B:"2", C:"3", D:"4"}, {A:"5", B:"6", C:"7", D:"8"}}

我一直在尝试使用以下代码:

import csv
import json

csvfile = open('test.csv','r')
jsonfile = open('test.json','w')

x = ("a","b","c","d")

reader = csv.DictReader(csvfile, x)
for row in reader:
    json.dump(row, jsonfile)

这段代码的输出结果如下:

{"a": "1", "null": ["5", "6", "7", "8", "9"], "c": "3", "b": "2", "d": "4"}

有人可以帮我解决这个问题吗?


输入不是csv文件。输出不是有效的json格式。您是指字典列表吗?[{A:”1”, B:”2”, C:”3”, D:”4”}, {A:”5”, B:”6”, C:”7”, D:”8”}] - falsetru
对不起..!! 是的,这是一个字典列表。 - naren
5个回答

36

处理完所有的行后进行数据转储。


import csv
import json

with open('test.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('test.json', 'w') as f:
    json.dump(rows, f)

@naren,我在发布之前进行了测试。它创建了一个名为test.json的文件,并将[{"A": "1", "C": "3", "B": "2", "D": "4"}, {"A": "5", "C": "7", "B": "6", "D": "8"}]作为内容。 - falsetru
1
明白了,非常感谢 @falsetru,相信您的指导会让我在Python方面取得优异的成绩。 - naren
实际上我正在尝试修改输入并进行检查,但我忘记选择正确的输入文件了。无论如何,谢谢@falsetru。 - naren
1
@falsetru 你不是在重新发明 DictReader 吗?谢谢。 - alecxe
太棒了!你懂了! - Mário de Sá Vera
显示剩余3条评论

4

这种方法会将每个键的**数值(int, float)转换为字符串(string)**。有什么解决办法吗? - user10634362

0

将CSV转换为Json Python

import csv
import urllib2

url = '<YOURCSVURL>'
response = urllib2.urlopen(url)
cr = csv.reader(response)

line = {}
data = []

for index, row in enumerate(cr):
    if index:
        for index, col in enumerate(row):
            line[name[index]] = col

        data.append(line.copy())
    else:
        name = row

print data

0
import csv
import json

# Constants to make everything easier
CSV_PATH = './csv.csv'
JSON_PATH = './json'

# Reads the file the same way that you did
csv_file = csv.DictReader(open(CSV_PATH, 'r'))

# Created a list and adds the rows to the list
json_list = []
for row in csv_file:
    json_list.append(row)

# Writes the json output to the file
file(JSON_PATH, 'w').write(json.dumps(json_list))

-3
您可以尝试使用以下代码进行操作:

def inputfunction(lists):
 tmpdict = {}
 for element_index in range(len(lists)):
     tmpdict[headers[elementindex]] = lists[element_index]
 return tmpdict

def run(filename):
 filelist = [eachline.split(',') for eachline in open(inputfile,'r')]
 headers = filelist[0]
 values = filelist[1:]
 finallist = []
 for lists in values:
     finallist.append(inputfunction(lists))
 return finallist

你的答案中的代码缩进不正确。此外,在run()函数末尾的for循环中的return语句只允许循环执行一次。 - martineau
1:缩进不正确。2:您只是创建了一个包含每个列表的字典,而这些列表并不是JSON格式。3:在您的“输入函数”中,还必须传递“headers”作为参数。4:在运行函数中,您必须将“filename”参数更改为“inputfile”或反之亦然。 - Paras jain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接