我有一个数据帧,我需要作为嵌套的json字符串传递给电子邮件服务提供程序api作为json字符串.
我的数据框看起来像这样:
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"]
}
我不确定如何通过pandas中的’to_json’命令创建嵌套的json字符串,同时将上面的单词“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)
最佳答案 使用to_dict()的orient =’records’格式化数据,然后将字典格式化为json
#converted emails to list, may not be necessary...
df.email_address = df.email_address.apply(lambda x: [x])
import json
update_contact = json.dumps({'import_data':df.to_dict(orient='records'),
'lists':["1234567890"]})