Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how to stringify JSON object when passing it as payload to request.post()

I have the following code in my Django view:

headers = {'Authorization': "key=AAAA7oE3Mj...",
               'Content-type': 'application/json'}
token  = "dJahuaU2p68:A..."
payload = {"data": {}, "to": user_web_tokens}
url = "https://..."
r = requests.post(url, data=payload, headers=headers)

The problem is that the response terminates with 400 error with the error message being:

JSON_PARSING_ERROR: Unexpected character (t) at position 0

If I pass a string instead of JSON:

payload = {"data": {}, "to": user_web_tokens}

...I get a slightly different error:

JSON_PARSING_ERROR: Unexpected character (u) at position 19.

I have come across a post where they say that a json object should be stringified before being passed on as a payload. But I have no idea how to this in Django. Does it have something to with serialization ? Help me please !

like image 416
Edgar Navasardyan Avatar asked Dec 23 '22 16:12

Edgar Navasardyan


1 Answers

when you post with nested dictionary data, json.dumps will help, or you can directly pass it via json parameter.

import json
# ...
r = requests.post(url, data=json.dumps(payload), headers=headers)
# or
r = requests.post(url, json=payload, headers=headers)

see the official docs.

like image 102
Leonard2 Avatar answered Feb 09 '23 00:02

Leonard2