CSV到JSON的Python块

时间:2019-03-11 04:51:39

标签: json python-3.x csv

我有以下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帮助实现这一目标的最佳方法?

3 个答案:

答案 0 :(得分: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"}

答案 1 :(得分: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

答案 2 :(得分:0)

我会使用愉快地集成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"}']