我有一个数据帧需要作为嵌套的json字符串作为json字符串传递到电子邮件服务提供者api中。
我的数据框如下所示:
email_address first_name last_name
a@a.com adam apple
b@b.com bobby banana
数据框中的联系人是我需要传递到电子邮件服务提供者API的,这需要是一个嵌套的JSON字符串,如下所示:
{
"import_data": [{
"email_addresses": ["hector@hector.com"],
"first_name": "Hector",
"last_name": "Smith"
}, {
"email_addresses": ["Jane@Doe.com"],
"first_name": "Jane",
"last_name": "Doe"
}, {
"email_addresses": ["Pradeep@Patel.com"],
"first_name": "Pradeep",
"last_name": "Patel"
}],
"lists": ["1234567890"]
}
我不确定如何通过' to_json'来创建嵌套的json字符串。来自pandas的命令,同时将上面的" import_data" 一词插入到json字符串中。我知道我可以在"列表" 的数据框中对列进行硬编码,并将其传入。列表ID始终是静态的。
以下是我的API响应的代码:
headers = {
'Authorization': '',
'X-Originating-Ip': '',
'Content-Type': '',
}
update_contact = '{"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]}'
r = requests.post('url', headers=headers ,data = update_contact)
print(r.text)
答案 0 :(得分:3)
我相信API要求application / json,如果确实如此,你应该像这样发送
headers = {}
update_contact = {"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]}
r = requests.post('url', headers=headers ,json= update_contact)
print(r.text)
答案 1 :(得分:2)
使用orient='records'
的{{1}}格式化数据,然后将字典格式化为json
to_dict()
答案 2 :(得分:1)
您可以使用json_variable.append(NewValues),以便将任何数据块附加到json值中。 请参阅下面的骨架并根据您的输入重新构建。
enter code here
import json
Json_List=[]
for i in Excel_data:
Newdata = {
'Name':Read_name_From_Excel(i),
'Age':Read_age_From_Excel(i),
'Email':Read_Email_From_Excel(i),
'Amount':Read_Amount_From_Excel(i)
}
Json_List.append(Newdata)