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

Posted

技术标签:

【中文标题】使用 Python 将 CSV 文件数据转换为 JSON 格式【英文标题】:Convert CSV file data into JSON format using Python 【发布时间】:2020-11-11 04:35:25 【问题描述】:

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

【问题讨论】:

client.write_points(json_body) -> 这应该在 for 循环中 :) 【参考方案1】:

我使用了您的实现并对其进行了一些更改。我不确定这是否正是您想要实现的目标

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)

【讨论】:

以上是关于使用 Python 将 CSV 文件数据转换为 JSON 格式的主要内容,如果未能解决你的问题,请参考以下文章

使用 Python 将 NetCDF 文件转换为 CSV 或文本

在将数据输入 FFT 用于音频频谱分析仪之前,使用 python 将 wav 文件转换为 csv 文件 [关闭]

Python - 将 csv 文件转换为 JSON

将CSV文件转换为xlsx文件Python

如何将导入 python 的数据从 csv 文件转换为时间序列?

使用 python 将 JSON 转换为 CSV