使用 Python 将 CSV 文件数据转换为 JSON 格式

Convert CSV file data into JSON format using Python

我的 CSV 文件中的数据很少。我想将此数据转换为 json 格式。通过使用下面的代码,我只能转换 CSV 文件的最后一行,但不能转换 CSV 数据的所有行。同样在我的 csv 文件中有很多列,但脚本只考虑第 3 列的值。

我可以看到 for 循环中需要更改,尝试了很多方法但没有成功,你能帮我解决这个问题吗?

我的脚本如下-

import pandas as pd
from influxdb import InfluxDBClient

client = InfluxDBClient(host='localhost', port=8086)
client.switch_database('csvdata')

file_path = r'/home/ec2-user/influxdb-1.4.2-1/LEGO_throughput.csv'

csvReader = pd.read_csv(file_path)

#print(csvreader.shape)
#print(csvreader.columns)

for row_index, row in csvReader.iterrows():
    tags = row[0]
    fieldvalue = row[2]
    json_body = [
    {
        "measurement": "LEGO_throughput",
        "tags": {
                "Reference": tags
        },
        "fields": {
            "value": fieldvalue
        }
    }
        ]

client.write_points(json_body)

和我的 CSV 数据 -

series(eventTimestamp),count(*),"percentile(responseTime, 95)",avg(responseTime)
2020-07-17T01:17:00+01:00,81,739,444.9753086
2020-07-17T01:18:00+01:00,784,2600,809.3762755
2020-07-17T01:19:00+01:00,3127,2825,1316.033259
2020-07-17T01:20:00+01:00,6348,2908,1421.663674

我使用了你的实现并做了一些修改。我不确定这是否正是您想要实现的

import pandas as pd
import json

file_path = r'./LEGO_throughput.csv'

csvReader = pd.read_csv(file_path)

#print(csvreader.shape)
#print(csvreader.columns)
json_body = []
for row_index, row in csvReader.iterrows():
    tags = row[0]
    fieldvalue = row[2]
    json_body += [
    {
        "measurement": "LEGO_throughput",
        "tags": {
                "Reference": tags
        },
        "fields": {
            "value": fieldvalue
        }
    }
        ]
with open("res.json", "w") as res:
    json.dump(json_body, res)