How to pass a variable in Json object while giving HTTP post request in Python

Question:

I am trying to pass a json object to one of my URLs which accepts the JSON data.

The code below works:

import requests

import json

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

Asked By: python_interest

||

Answers:

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.

Answered By: blhsing

Use json.dumps:

payloads = {"message": s}

r = requests.post(url, data=json.dumps(payloads), headers=headers)
Answered By: pfctgeorge

rec is the variable whose value I wanted to print

url = "abc.com"
payload = '{"text":"' +str(rec)+ '"}'
r = requests.post(url,data=payload)
Answered By: Anushka Arora