對于 Python 專業人士來說,這可能是一個簡單的方法。所以,請原諒我的天真。
這是我的資料:
0 [email protected] 13239169023 jane bo
1 [email protected] 13239169023 lane ko
2 [email protected] 13239169023 john do
這是我得到的輸出:
[{"email":"[email protected]","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"[email protected]","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"[email protected]","phone_number":13239169023,"first_name":"john","last_name":"do"}]
我的代碼:
df = pd.read_csv('profiles.csv')
print(df)
data = df.to_json(orient="records")
print(data)
我想要的輸出:
{"profiles":[{"email":"[email protected]","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"[email protected]","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"[email protected]","phone_number":13239169023,"first_name":"john","last_name":"do"}]}
添加下面不起作用。
output = {"profiles": data}
它在非雙引號中的資料和組態檔上添加單引號(基本上不是有效的 JSON),如下所示:
{'profiles': '[{"email":"[email protected]","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"[email protected]","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"[email protected]","phone_number":13239169023,"first_name":"john","last_name":"do"}]'}
uj5u.com熱心網友回復:
您可以使用df.to_dict輸出到字典而不是 json 格式的字串:
import pandas as pd
df = pd.read_csv('data.csv')
data = df.to_dict(orient='records')
output = {'profiles': data}
print(output)
回傳:
{'profiles': [{'0': 1, '[email protected]': '[email protected]', '13239169023': 13239169023, 'jane': 'lane', 'bo': 'ko'}, {'0': 2, '[email protected]': '[email protected]', '13239169023': 13239169023, 'jane': 'john', 'bo': 'do'}]}
uj5u.com熱心網友回復:
我想我找到了解決辦法。
變化:
data = df.to_dict(orient="records")
output = {}
output["profiles"] = data
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/402293.html
標籤:
