在python中将CSV转换为JSON文件

nhjlsmyf  于 2023-04-27  发布在  Python
关注(0)|答案(4)|浏览(252)


包含近2000行的csv文件。
我想逐行解析CSV文件并将其转换为JSON并通过WebSocket发送。
我在网上找到了一些将CSV转换为JSON的代码,如下所示:

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')

但是上面代码的问题是我们需要提到字段名来解析CSV。因为我有超过2000行,这不是一个可行的解决方案。
有人能建议如何逐行解析CSV文件并将其转换为JSON而无需指定字段名吗?

im9ewurl

im9ewurl1#

Python CSV转JSON

要在Python中将CSV转换为JSON,请执行以下步骤:
1.初始化Python列表。
1.使用csv.DictReader()函数读取CSV文件的行。
1.将每一行转换为一个字典。将字典添加到步骤1中创建的Python列表中。
1.使用json.dumps()将Python列表转换为JSON字符串。
1.您可以将JSON字符串写入JSON文件。

data.csv

  • 在测试中,我使用复制/粘贴在一个csv文件中创建了100.000行,使用Apple's M1 Chip时,整个转换过程大约需要半秒,而本示例只需要0.0005秒。

column_1,column_2,column_3
value_1_1,value_1_2,value_1_3
value_2_1,value_2_2,value_2_3
value_3_1,value_3_2,value_3_3

Python程序

import csv 
import json
import time

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []
      
    #read csv file
    with open(csvFilePath, encoding='utf-8') as csvf: 
        #load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf) 

        #convert each csv row into python dict
        for row in csvReader: 
            #add this python dict to json array
            jsonArray.append(row)
  
    #convert python jsonArray to JSON String and write to file
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)
          
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'

start = time.perf_counter()
csv_to_json(csvFilePath, jsonFilePath)
finish = time.perf_counter()

print(f"Conversion 100.000 rows completed successfully in {finish - start:0.4f} seconds")

输出:data.json

Conversion 100.000 rows completed successfully in 0.5169 seconds
[
    {
        "column_1": "value_1_1",
        "column_2": "value_1_2",
        "column_3": "value_1_3"
    },
    {
        "column_1": "value_2_1",
        "column_2": "value_2_2",
        "column_3": "value_2_3"
    },
    {
        "column_1": "value_3_1",
        "column_2": "value_3_2",
        "column_3": "value_3_3"
    }
]
kkbh8khc

kkbh8khc2#

你可以试试这个:

import csv 
import json 

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []
      
    with open(csvFilePath, encoding='utf-8') as csvf: 
        csvReader = csv.DictReader(csvf) 

        for row in csvReader: 
            jsonArray.append(row)
  
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)
          
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)

我转换了一个200MB的文件,有600K+行,它工作得很好。

6g8kf2rb

6g8kf2rb3#

假设您的CSV有一个标题行:只需从DictReader中删除fieldnames参数
如果省略fieldnames参数,则文件f的第一行中的值将用作fieldnames。

import csv
import json

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

reader = csv.DictReader(csvfile)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')
vbkedwbf

vbkedwbf4#

如果你对你的解决方案很满意,唯一困扰你的是如何输入列标题的‘长‘列表,我建议你使用类似www. example. com()的东西阅读CSV的第一(标题)行reader.next,

import csv

with open('your_CSV.csv') as csvFile:
    reader = csv.reader(csvFile)
    field_names_list = reader.next()

然后使用str.split(',')将所获得的字符串拆分为列表。
您得到的列表可以被馈送到

fieldnames = (---from the above code block ---)

你的代码行。

相关问题