对于 Python 专业人士来说,这可能是一个简单的方法。所以,请原谅我的天真。
这是我的资料:
0 xyz@tim.com 13239169023 jane bo
1 tim@tim.com 13239169023 lane ko
2 jim@jim.com 13239169023 john do
这是我得到的输出:
[{"email":"xyz@tim.com","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"tim@tim.com","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"jim@jim.com","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":"xyz@tim.com","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"tim@tim.com","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"jim@jim.com","phone_number":13239169023,"first_name":"john","last_name":"do"}]}
添加下面不起作用。
output = {"profiles": data}
它在非双引号中的资料和组态档上添加单引号(基本上不是有效的 JSON),如下所示:
{'profiles': '[{"email":"xyz@tim.com","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"tim@tim.com","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"jim@jim.com","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, 'xyz@tim.com': 'tim@tim.com', '13239169023': 13239169023, 'jane': 'lane', 'bo': 'ko'}, {'0': 2, 'xyz@tim.com': 'jim@jim.com', '13239169023': 13239169023, 'jane': 'john', 'bo': 'do'}]}
uj5u.com热心网友回复:
我想我找到了解决办法。
变化:
data = df.to_dict(orient="records")
output = {}
output["profiles"] = data
0 评论