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 a@a.com adam apple b@b.com 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": ["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"] }
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": ["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)
3 Answers
Answers 1
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": ["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)
Answers 2
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"]})
Answers 3
You can use json_variable.append(NewValues) so that it will append any of your data blocks into a json value. Refer to below skeleton and re-build according to your inputs.
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)
0 comments:
Post a Comment