Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass nested JSON from dataframe while adding another field?

I have a dataframe that I need to pass as a nested json string into an email service provider api as a json string.

My dataframe looks like this:

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

The contacts in the dataframe is what I need to pass into the email service provider API, and this needs be a nested JSON string like so:

{
    "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"]
}

I am not sure how I would create nested json string via the 'to_json' command from pandas and at the same time insert the word "import_data" as above into the json string. I know I can hard code the a column with in the dataframe for "lists" and pass that in as well. List ID will always be static.

Here is code for my API response:

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)
like image 224
RustyShackleford Avatar asked Mar 22 '26 13:03

RustyShackleford


2 Answers

I believe the API asked for application/json, if this is really the case, you should send it like this

headers = {}

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 ,json= update_contact)

print(r.text)
like image 71
Gabriel B.R Avatar answered Mar 24 '26 21:03

Gabriel B.R


Format the data using orient='records' of to_dict(), then just format your the dictionary to 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"]})
like image 20
DJK Avatar answered Mar 24 '26 21:03

DJK