How to pass a variable in Json object while giving HTTP post request
18,679
You should include double quotes around the string in your JSON object:
payload='{"message":"' +str(s)+ '"}'
so that payload
would become '{"message": "hello"}'
.
Otherwise payload
would become '{"message": hello}'
with your current code.
Author by
python_interest
Updated on June 04, 2022Comments
-
python_interest almost 2 years
I am trying to pass the json object to one of my URLs which accepts the JSON data.
The below works:
payload='{"message": "hello"}' headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'} r = requests.post(url, data=payload, headers=headers)
r.text is giving me "hello"
But when I tried to pass the variable
s="hello" payload='{"message":' +str(s)+ '}' headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'} r = requests.post(url, data=payload, headers=headers)
The above didnt work. When I tried to load as a JSON, it is throwing me error as well
payload=json.loads(payload) JSONDecodeError: Expecting value: line 1 column 12 (char 11)
Also I wanted to pass b'blahblah' as a JSON message. Since passing a string didnt work for me, I didnt attempt to pass bytes format.
Please advice
-
python_interest over 5 yearsI dont know why this was down voted. This worked for me :) . Is it possible to send the bytes in JSON object ? For me the image is going to be my JSON. Is there any way to send bytes to JSON?
-
blhsing over 5 yearsJSON is meant for texts. You can encode images into texts with
base64
if you insist though.