简体   繁体   English

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

[英]Convert CSV file data into JSON format using Python

I have few data in a CSV file. CSV 文件中的数据很少。 I wanted to convert this data into json format.我想将此数据转换为 json 格式。 By using the below code i am able to convert only last line of my CSV file, but not all rows of CSV data.通过使用下面的代码,我只能转换 CSV 文件的最后一行,但不能转换 CSV 数据的所有行。 Also in my csv file there are many columns but script is considering only column 3 values.同样在我的 csv 文件中有很多列,但脚本只考虑第 3 列的值。

I could see that the change is required in for loop, Tried many ways but didnt succeeded can you please help me in resolving this issue?我可以看到 for 循环中需要更改,尝试了很多方法但没有成功你能帮我解决这个问题吗?

My script is below -我的脚本如下 -

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)

and my CSV data -和我的 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

I used your implementation and changed it a bit.我使用了您的实现并对其进行了一些更改。 I am not sure if it's exactly what you wanted to achieve我不确定这是否正是您想要实现的目标

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM