CSV数据(非文件)到json

时间:2019-07-04 17:34:17

标签: json python-3.x csv

我正在通过python请求模块使用API​​,该模块返回CSV格式的数据。我不想将数据写入文件,因为我正试图将此过程转换为GCP上的无服务器功能,因此不必创建文件就只能一次读取一行。来自邮递员的回复数据如下所示:

    "completed","email","role","first","last","title","company","AccountName","AccountNumber","City","Description","State","Street","Zip","agreementId"
    "2019-07-04 10:14:28","echosmusz1+signer1@gmail.com","SIGNER","Sam","Signerone","Title","","Sam,s Garage","654654","Cityville","Some description here, with commas.","CA","123 South Main","98673","CBJCHBCAABAAcvZGncvMUCUf9XqXr1fwCGmKctFn_qIS"

它可能有一行以上的数据,但标头始终是第一行。

我可以除以\n,但想知道哪种最好,最有效的方法将其作为JSON返回?

1 个答案:

答案 0 :(得分:1)

尝试使用熊猫。首先阅读类似CSV的字符串,然后转换为JSON:

from io import StringIO
import pandas as pd

csv_data = StringIO("""
"completed","email","role","first","last","title","company","AccountName","AccountNumber","City","Description","State","Street","Zip","agreementId"
"2019-07-04 10:14:28","echosmusz1+signer1@gmail.com","SIGNER","Sam","Signerone","Title","","Sam,s Garage","654654","Cityville","Some description here, with commas.","CA","123 South Main","98673","CBJCHBCAABAAcvZGncvMUCUf9XqXr1fwCGmKctFn_qIS"
""")

df = pd.read_csv(csv_data)
json_data = df.to_json(orient='records')

print(json_data)
# [{"completed":"2019-07-04 10:14:28","email":"echosmusz1+signer1@gmail.com","role":"SIGNER","first":"Sam","last":"Signerone","title":"Title","company":null,"AccountName":"Sam,s Garage","AccountNumber":654654,"City":"Cityville","Description":"Some description here, with commas.","State":"CA","Street":"123 South Main","Zip":98673,"agreementId":"CBJCHBCAABAAcvZGncvMUCUf9XqXr1fwCGmKctFn_qIS"}]