微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在添加另一个字段时从数据框传递嵌套的JSON?

我有一个数据帧,我需要作为嵌套的json字符串传递给电子邮件服务提供程序api作为json字符串.

我的数据框看起来像这样:

email_address     first_name       last_name
[email protected]            adam             apple
[email protected]            bobby            banana

我需要将数据框中的联系人传递到电子邮件服务提供程序API,这需要是嵌套的JSON字符串,如下所示:

{
    "import_data": [{
        "email_addresses": ["[email protected]"],
        "first_name": "Hector",
        "last_name": "Smith"
    }, {
        "email_addresses": ["[email protected]"],
        "first_name": "Jane",
        "last_name": "Doe"
    }, {
        "email_addresses": ["[email protected]"],
        "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": ["[email protected]"],"first_name": "test","last_name": "test"},{"email_addresses": ["[email protected]"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["[email protected]"],"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"]})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐