Using python 'requests' to send JSON boolean
23,473
Solution 1
You need to json encode it to get it to a string.
import json
payload = json.dumps({"on":True})
Solution 2
should be {'on': True}, capital T
Solution 3
Starting from requests 2.4.2, instead of passing in the payload with the data
parameter, you can use the json
parameter like this:
payload = {'on': True}
requests.put(url, json=payload)
And the request will be formatted correctly as a json payload (i.e. {'on': true}
).
Related videos on Youtube
Author by
Erik Pragt
Updated on July 01, 2021Comments
-
Erik Pragt almost 3 years
I've got a really simple question, but I can't figure it out how to do it. The problem I have is that I want to send the following payload using Python and Requests:
{ 'on': true }
Doing it like this:
payload = { 'on':true } r = requests.put("http://192.168.2.196/api/newdeveloper/lights/1/state", data = payload)
Doesn't work, because I get the following error:
NameError: name 'true' is not defined
Sending the true as 'true' is not accepted by my server, so that's not an option. Anyone a suggestion? Thanks!
-
GP89 almost 11 years
True
on python is spelt with a capital 'T' :) -
lunaryorn almost 11 yearsUhm, it's
True
in Python... -
Erik Pragt almost 11 yearsI know that it's True. But when I put 'True' there, the payload will be "{'on': True}". I want it to be "{'on': true}"
-
GP89 about 6 years@OmPrakash GET data has to be a string yes, it's just part of the URL. if you are using json you can just use
json.loads(data)
to convert it back on the server, or whichever appropriate deserialisation.
-
-
Erik Pragt almost 11 yearsThat doesn't work. I want the payload to be {'on':true}. This will turn the payload into {'on':True}, which unfortunately doesn't work.
-
Conan Li almost 11 yearsthat is because you need to dump the dictionary using json. For example, when you have payload={"on": True}, do json.dumps(payload)
-
RICHA AGGARWAL almost 8 yearsPassing a proper Boolean object helped us ie True / False
-
Justin Farrugia about 5 yearsdoesn't this still give out "on" and "True" ?