CSV文件到Python中的JSON文件

时间:2012-10-18 09:26:31

标签: python json csv

我在这里和其他地方已经阅读了很多帖子,但我似乎无法找到解决方案。而且我不想在线转换它。

我想将CSV文件转换为JSON文件(没有嵌套,即使我以后可能需要它),我发现here的代码:

import csv
import json

f = open( 'sample.csv', 'r' )
reader = csv.DictReader( f, fieldnames = ( "id","name","lat","lng" ) )
out = json.dumps( [ row for row in reader ] )
print out

很棒,简单,而且很有效。但我没有得到.csv文件,但是如果我复制和粘贴的文本输出是一个长行。

我需要一个可读的.json,理想情况下保存到.json文件中。 这可能吗?

3 个答案:

答案 0 :(得分:3)

要获得更具可读性的JSON,请尝试indent中的dumps()参数:

print json.dumps(..., indent=4)

但是 - 看起来更像原始的CSV文件,你可能想要的是分别对每一行进行编码,然后使用JSON数组语法将它们全部连接起来:

out = "[\n\t" + ",\n\t".join([json.dumps(row) for row in reader]) + "\n]"

那应该给你一些:

[
    {"id": 1, "name": "foo", ...},
    {"id": 2, "name": "bar", ...},
    ...
]

如果您需要帮助将结果写入文件,请尝试this tutorial

答案 1 :(得分:1)

如果您想要更可读的JSON文件格式,请使用它:

json.dump(output_value, open('filename','w'), indent=4, sort_keys=False)

答案 2 :(得分:1)

这是一个完整的脚本。此脚本使用第一行的逗号分隔值作为JSON输出的键。输出JSON文件将使用与输入CSV文件名相同的文件名自动创建或覆盖,只需将.csv文件扩展名替换为.json。

CSV文件示例:

id,longitude,latitude
1,32.774,-124.401
2,32.748,-124.424
4,32.800,-124.427
5,32.771,-124.433

Python脚本:

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

jsonfile.write('{"' + 'sample.csv'.replace('.csv', '') + '": [\n') # Write JSON parent of data list
fieldnames = csvfile.readline().replace('\n','').split(',')        # Get fieldnames from first line of csv
num_lines = sum(1 for line in open('sample.csv')) - 1              # Count total lines in csv minus header row

reader = csv.DictReader(csvfile, fieldnames)
i = 0
for row in reader:
  i += 1
  json.dump(row, jsonfile)
  if i < num_lines:
    jsonfile.write(',')
  jsonfile.write('\n')
jsonfile.write(']}')