Python中的CSV到JSON块

问题描述 投票:0回答:3

我有以下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来帮助实现这个目标吗?

json python-3.x csv
3个回答
1
投票

这可能对你有帮助.. 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"}

0
投票

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

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

0
投票

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

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"}']
© www.soinside.com 2019 - 2024. All rights reserved.