115

这是我的代码,非常简单的东西......

import csv
import json

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

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
out = json.dumps( [ row for row in reader ] )
jsonfile.write(out)

声明一些字段名,阅读器使用 CSV 读取文件,文件名将文件转储为 JSON 格式。这就是问题所在...

CSV 文件中的每条记录位于不同的行上。我希望 JSON 输出以相同的方式。问题是它把它全部倾倒在一条巨大的长线上。

我试过使用类似的东西for line in csvfile:,然后在下面运行我的代码reader = csv.DictReader( line, fieldnames),循环遍历每一行,但它在一行上执行整个文件,然后在另一行上循环遍历整个文件......继续直到它用完行.

有什么建议可以纠正这个问题吗?

编辑:澄清一下,目前我有:(第 1 行的每条记录)

[{"FirstName":"John","LastName":"Doe","IDNumber":"123","Message":"None"},{"FirstName":"George","LastName":"Washington","IDNumber":"001","Message":"Something"}]

我在找什么:(2 行 2 条记录)

{"FirstName":"John","LastName":"Doe","IDNumber":"123","Message":"None"}
{"FirstName":"George","LastName":"Washington","IDNumber":"001","Message":"Something"}

不是每个单独的字段都缩进/在单独的行上,而是每个记录都在它自己的行上。

一些样本输入。

"John","Doe","001","Message1"
"George","Washington","002","Message2"
4

12 回答 12

166

您所需输出的问题是它不是有效的 json 文档;这是一个json 文件流

没关系,如果它是您需要的,但这意味着对于您想要在输出中的每个文档,您必须调用json.dumps.

由于您要分隔文档的换行符不包含在这些文档中,因此您必须自己提供它。所以我们只需要将循环从对 json.dump 的调用中拉出来,并为每个写入的文档插入换行符。

import csv
import json

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

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')
于 2013-10-31T12:49:43.453 回答
38

您可以使用 Pandas DataFrame 来实现此目的,示例如下:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)
于 2017-02-02T12:13:15.300 回答
14
import csv
import json

file = 'csv_file_name.csv'
json_file = 'output_file_name.json'

#Read CSV File
def read_CSV(file, json_file):
    csv_rows = []
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        field = reader.fieldnames
        for row in reader:
            csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
        convert_write_json(csv_rows, json_file)

#Convert csv data into json
def convert_write_json(data, json_file):
    with open(json_file, "w") as f:
        f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))) #for pretty
        f.write(json.dumps(data))


read_CSV(file,json_file)

json.dumps() 的文档

于 2018-01-06T19:58:46.033 回答
12

我接受了@SingleNegationElimination 的响应并将其简化为可在管道中使用的三线:

import csv
import json
import sys

for row in csv.DictReader(sys.stdin):
    json.dump(row, sys.stdout)
    sys.stdout.write('\n')
于 2015-11-25T22:25:17.383 回答
7

你可以试试这个

import csvmapper

# how does the object look
mapper = csvmapper.DictMapper([ 
  [ 
     { 'name' : 'FirstName'},
     { 'name' : 'LastName' },
     { 'name' : 'IDNumber', 'type':'int' },
     { 'name' : 'Messages' }
  ]
 ])

# parser instance
parser = csvmapper.CSVParser('sample.csv', mapper)
# conversion service
converter = csvmapper.JSONConverter(parser)

print converter.doConvert(pretty=True)

编辑:

更简单的方法

import csvmapper

fields = ('FirstName', 'LastName', 'IDNumber', 'Messages')
parser = CSVParser('sample.csv', csvmapper.FieldMapper(fields))

converter = csvmapper.JSONConverter(parser)

print converter.doConvert(pretty=True)
于 2015-02-08T15:20:06.690 回答
4

我看到这很旧,但我需要 SingleNegationElimination 的代码,但是我遇到了包含非 utf-8 字符的数据的问题。这些出现在我不太关心的领域,所以我选择忽略它们。然而,这需要一些努力。我是 python 新手,所以经过反复试验,我让它工作了。该代码是 SingleNegationElimination 的副本,带有对 utf-8 的额外处理。我试图用https://docs.python.org/2.7/library/csv.html来做,但最后放弃了。下面的代码有效。

import csv, json

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

fieldnames = ("Scope","Comment","OOS Code","In RMF","Code","Status","Name","Sub Code","CAT","LOB","Description","Owner","Manager","Platform Owner")
reader = csv.DictReader(csvfile , fieldnames)

code = ''
for row in reader:
    try:
        print('+' + row['Code'])
        for key in row:
            row[key] = row[key].decode('utf-8', 'ignore').encode('utf-8')      
        json.dump(row, jsonfile)
        jsonfile.write('\n')
    except:
        print('-' + row['Code'])
        raise
于 2016-08-18T15:50:42.513 回答
3

indent参数添加到json.dumps

 data = {'this': ['has', 'some', 'things'],
         'in': {'it': 'with', 'some': 'more'}}
 print(json.dumps(data, indent=4))

另请注意,您可以简单地使用json.dumpopen jsonfile

json.dump(data, jsonfile)
于 2013-10-31T03:17:40.443 回答
2

如何使用 Pandas 将 csv 文件读入 DataFrame ( pd.read_csv ),然后根据需要操作列(删除它们或更新值),最后将 DataFrame 转换回 JSON ( pd.DataFrame.to_json )。

注意:我还没有检查过它的效率如何,但这绝对是操作大型 csv 并将其转换为 json 的最简单方法之一。

于 2016-07-07T17:10:20.380 回答
2

使用 pandas 和 json 库:

import pandas as pd
import json
filepath = "inputfile.csv"
output_path = "outputfile.json"

df = pd.read_csv(filepath)

# Create a multiline json
json_list = json.loads(df.to_json(orient = "records"))

with open(output_path, 'w') as f:
    for item in json_list:
        f.write("%s\n" % item)
于 2021-02-08T20:08:55.923 回答
0

作为对@MONTYHS 答案的轻微改进,遍历一组字段名:

import csv
import json

csvfilename = 'filename.csv'
jsonfilename = csvfilename.split('.')[0] + '.json'
csvfile = open(csvfilename, 'r')
jsonfile = open(jsonfilename, 'w')
reader = csv.DictReader(csvfile)

fieldnames = ('FirstName', 'LastName', 'IDNumber', 'Message')

output = []

for each in reader:
  row = {}
  for field in fieldnames:
    row[field] = each[field]
output.append(row)

json.dump(output, jsonfile, indent=2, sort_keys=True)
于 2014-03-05T19:43:35.903 回答
0
def read():
    noOfElem = 200  # no of data you want to import
    csv_file_name = "hashtag_donaldtrump.csv"  # csv file name
    json_file_name = "hashtag_donaldtrump.json"  # json file name

    with open(csv_file_name, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        with open(json_file_name, 'w') as json_file:
            i = 0
            json_file.write("[")
            
            for row in csv_reader:
                i = i + 1
                if i == noOfElem:
                    json_file.write("]")
                    return

                json_file.write(json.dumps(row))

                if i != noOfElem - 1:
                    json_file.write(",")

改变上面三个参数,一切就搞定了。

于 2021-01-21T18:40:36.897 回答
-1
import csv
import json
csvfile = csv.DictReader('filename.csv', 'r'))
output =[]
for each in csvfile:
    row ={}
    row['FirstName'] = each['FirstName']
    row['LastName']  = each['LastName']
    row['IDNumber']  = each ['IDNumber']
    row['Message']   = each['Message']
    output.append(row)
json.dump(output,open('filename.json','w'),indent=4,sort_keys=False)
于 2013-10-31T12:03:05.403 回答