Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python 'requests' to send JSON boolean

Tags:

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!

like image 391
Erik Pragt Avatar asked Jul 31 '13 20:07

Erik Pragt


People also ask

Can I send boolean in JSON?

Short answer, yes that is the proper way to send the JSON. You should not be placing anything other than a string inside of quotes. As for your bool value, if you want it to convert straight into a bool, than you do not need to include the quotes.

How do you send a JSON response in Python?

To post a JSON to the server using Python Requests Library, call the requests. post() method and pass the target URL as the first parameter and the JSON data with the json= parameter. The json= parameter takes a dictionary and automatically converts it to a JSON string.

What is bool in JSON?

The boolean type matches only two special values: true and false . Note that values that evaluate to true or false , such as 1 and 0, are not accepted by the schema.


1 Answers

You need to json encode it to get it to a string.

import json  payload = json.dumps({"on":True}) 
like image 124
GP89 Avatar answered Sep 28 '22 05:09

GP89