Search code examples
pythonjsonpandaspython-requestsapi-design

How to drop single quotes, and add brackets into pandas dataframe after converting to_json?


I have successfully converted a pandas dataframe into a json string while adding the string 'import_data' at the beginning like so:

a = {"import_data" : df.to_json(orient='records')}

This returns:

{'import_data': '[{"\\ufeffemail_addresses":"[email protected]","first_name":"test","last_name":"test","lists":1234567890},{"\\ufeffemail_addresses":"[email protected]","first_name":"Jane","last_name":"Doe","lists":1234567890},{"\\ufeffemail_addresses":"[email protected]","first_name":"Pradeep","last_name":"Patel","lists":1234567890}]'}

However pandas 'to_json', isnt converting the dataframe exactly too what I need to pass into an API.

The string need, has to look like this:

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

to_json is adding single quote around the first bracket, adding backslashes for some reason, the letter 'u', and a string \\ufeffat the beginning of email_address. Not sure how to drop all of this.

Edit:

This is how I can only pass data into the API:

headers = {

        'Authorization': 'Bearer x',
        'X-Originating-Ip': 'x',
        'Content-Type': 'application/json',

        }


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": ["1072830671"]}'

r_3 = requests.post('urlapi_key=x', headers=headers ,data = update_contact)

Solution

  • Try the following code.

    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\"]}'
    

    We can use backslash\before doublequote " to print it like this \"