【问题标题】:Convert CSV to JSON file in python在python中将CSV转换为JSON文件
【发布时间】:2019-05-13 13:39:00
【问题描述】:

以上包含近 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?

【问题讨论】:

  • 所以你想要一个 json 数组,其中该数组中的每个元素都是转换为 json 的 CSV 行?
  • DictReader的fieldnames参数是可选的,如果省略,则读取文件的第一行以获取字段名称
  • 是的。逐行读取CSV并将该行转换为json,发送到websocket。
  • 注意:所谓的 json 文件不会包含有效的 JSON 数据。您必须逐行阅读并单独解析每一行。

标签: python json csv parsing


【解决方案1】:

Python CSV 转 JSON

要在 Python 中将 CSV 转换为 JSON,请执行以下步骤:

  1. 初始化 Python 列表。
  2. 使用csv.DictReader()函数读取CSV文件的行。
  3. 将每一行转换为字典。将字典添加到第 1 步中创建的 Python 列表中。
  4. 使用 json.dumps() 将 Python 列表转换为 JSON 字符串。
  5. 您可以将 JSON 字符串写入 JSON 文件。

数据.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"
    }
]

【讨论】:

    【解决方案2】:

    假设您的 CSV 有一个标题行:只需从 DictReader 中删除 fieldnames 参数

    如果省略 fieldnames 参数,文件 f 的第一行中的值将用作字段名。 在https://docs.python.org/2/library/csv.html

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

    【讨论】:

    • 上述过程的问题是它认为列值是字符串而不是整数或浮点数。
    【解决方案3】:

    如果您对现有的解决方案感到满意,并且唯一困扰您的是如何输入列标题的“长”列表,我建议您使用类似阅读器的方式阅读 CSV 的第一(标题)行.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 ---)
    

    你的代码行。

    【讨论】:

    • 正如我在问题中提到的,我不想写字段名称,因为我有超过 2000 个字段。
    • 我明白这一点。这就是我上面的解决方案所做的。您不必自己键入字段名称。只需从上面的第一个代码块中获取列表,并将其提供给变量 'fieldnames'
    【解决方案4】:

    你可以试试这个:

    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)
    

    我转换了一个包含 600K+ 行的 200MB 文件,效果很好。

    【讨论】:

      猜你喜欢
      • 2015-01-13
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2017-11-30
      • 2018-03-06
      • 2019-08-15
      • 1970-01-01
      • 2018-07-14
      相关资源
      最近更新 更多