如何从 CSV 文件制作 JSON 文件?

How can I make JSON file from a CSV?

我有一个包含 4 列(A、B、C、D)的 CSV 文件。像这样:

A B C D
Example english text Translated text Context Max Length
Example english text 2 Translated text 2 Context 2 Max Length 2
Example english text 3 Translated text 3 Context 3 Max Length 3

我需要一个代码,将其转换为这个 JSON 文件:

{
  "Context": "Translated text",
  "Context 2": "Translated text 2",
  "Context 3": "Translated text 3"
}

我试过这个:

import csv
import json


def make_json(csvFilePath, jsonFilePath):
    
    data = {}
    
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        
        for rows in csvReader:
            
            key = rows["C"]
            data[key] = rows


    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))
        

csvFilePath = "main.csv"
jsonFilePath = "test.json"

make_json(csvFilePath, jsonFilePath)

但是有一个错误,我不确定这是最好的方法。

我该如何解决这个问题?

错误:

D:\Python\CSV to JSON>py csvtojson.py
Traceback (most recent call last):
  File "D:\Python\CSV to JSON\csvtojson.py", line 25, in <module>
    make_json(csvFilePath, jsonFilePath)
  File "D:\Python\CSV to JSON\csvtojson.py", line 14, in make_json
    key = rows["C"]
KeyError: 'C'

感谢您的帮助!

你可以用 Pandas 来做,你用很少的代码行就晚了。

import pandas as pd
# Read the csv file into Python with help from Pandas
df = pd.read_csv('csv-file.csv')

# Work with your json data in Python
json_data = df.to_json(orient = 'records')

# Save your data into new json file
df.to_json("path\example.json", orient = 'records')

然后将 CSV 文件加载到 python 并将其转换为 JSON,就可以开始了! :)

如果您没有 pandas 只需将其输入

pip install pandas

应该这样做-

import csv

with open('data.csv', 'r') as f:
    csv_data = csv.reader(f)
    json_data = {data[2]: data[1] for data in csv_data}
    
with open('data.json', 'w') as f:
    json.dump(json_data, f, indent=4)