我正在将csv转换为json并进行格式化,但是我无法使用len,next或切片方法来工作。因此,我对如何获得它不知所措,不添加最后一个逗号。
看起来像这样:
reader = csv.DictReader(csvfile, fieldnames)
jsonfile.write("[")
for row in reader:
sum += 1
json.dump(row, jsonfile)
if sum == len(reader):
jsonfile.write(",")
jsonfile.write("\n")
else:
jsonfile.write("\n")
jsonfile.write("]")
答案 0 :(得分:1)
无需处理终止每一行文字或防止出现最后的逗号,而可以在csv.DictReader的每一行的列表理解中使用json.dumps,并且将全部处理:
import csv
import json
with open( '/path/to/filename.csv', 'r' ) as csvfile:
reader = csv.DictReader( csvfile, fieldnames = ("fn_a","fn_b","fn_c"))
jsonfile = json.dumps( [ row for row in reader ] )
with open('output.json', 'w') as f:
f.write(jsonfile)