繁体   English   中英

CSV到JSON的Python块

[英]CSV to JSON blocks in Python

我有以下csv文件。

Occurrences,post_title,ID, System
1, Test 7, 34, Abc
2, Test 9, 55, Xyz
5, Test 11, 87, Pqy
7, Test 3, 71, Cde

问:我想遍历循环并将每一行作为JSON块发送到API。 例如,我要发送的第一次迭代如下。 {"occurrences": "1", "post_title": "Test 7", "ID" : "34", "System" : "Abc"}

我要发送的第二次迭代如下。 {"occurrences": "2", "post_title": "Test 9", "ID" : "55", "System" : "Xyz"}

等等...

您能否以Python帮助实现这一目标的最佳方法?

这可能对您有帮助。csv.DictReader将为您提供有序的字典:)

import csv
import json
input_file = csv.DictReader(open("testing_sid.csv"))
for row in input_file:
    out = json.dumps(row)
    print(out)

输出:-

{"Occurrences": "1", "post_title": " Test 7", "ID": " 34", "System": " Abc"}
{"Occurrences": "2", "post_title": " Test 9", "ID": " 55", "System": " Xyz"}
{"Occurrences": "5", "post_title": " Test 11", "ID": " 87", "System": " Pqy"}
{"Occurrences": "7", "post_title": " Test 3", "ID": " 71", "System": " Cde"}

我认为这可以解决您的问题

import pandas as pd
import json
def get_json(csv_path):
    tabel = pd.read_csv(csv_path)
    row_list = tabel.to_dict('records')
    result = json.dumps(row_list)
    return result

我会使用愉快地集成CSV和JSON支持的熊猫:

import pandas as pd
df = pd.read_csv("your_file.csv")
result = df.apply(lambda x: x.to_json(), axis=1).tolist()
#['{"Occurrences":1,"post_title":" Test 7","ID" ... "System":" Cde"}']

暂无
暂无

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

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