Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can/should boolean values be passed in json with quotes?

Tags:

json

boolean

I've read through a few questions on this and I'm still unclear. Which is correct:

{"some_parameter": "true"}

or

{"some_parameter": true}

I assume the second is the correct, proper way to send boolean values via json? But the first is still valid json...

The context here is that I'm building an API (used by some 3rd party applications) and I'm wondering if it's reasonable to simply disallow the first type altogether (reject with error) or accept boolean data as strings like this, and just attempt to handle (convert) them?

like image 661
Inigo Avatar asked Aug 20 '18 18:08

Inigo


People also ask

How is true boolean value represented in JSON?

In Python, "boolean" is analogous to bool . Note that in JSON, true and false are lower case, whereas in Python they are capitalized ( True and False ).

Are boolean values enclosed in quotes?

String values must be enclosed in quotation marks and may contain backslash escape characters. Numeric values are not enclosed in quotation marks. A boolean value is either true or false, and is not enclosed in quotation marks.


2 Answers

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.

Long answer,

It depends on the data type. For the Key, yes you have to use quotes but only for strings. Also, you can use single quotes if you want to place a quotation mark inside of it. (or use escape)

' 

for instance, vs

"

As for your bool value, if you want it to convert straight into a bool, than you do not need to include the quotes. Same for integers and double values.

But if you want to pass it as a string, than you will need to put it inside of quotes.

Generally, these types of questions are asked when you discuss what types of systems will be accepting your data.

It's generally much easier to use strings everywhere, but it's also extremely inefficient and results in your recipient needing to cast them if they want to do arithmetic with an int for instance, but it's passed as a string.

like image 176
Jacob Gaiski Avatar answered Sep 23 '22 14:09

Jacob Gaiski


Boolean values must be passed without quotes. Boolean is one of the types supported by json: https://www.json.org/json-en.html and the expected values are true or false, without quotes.

It may still work with quotes when the receiving end parsing the data is a weak typing language like Javascript which converts the value automatically when you use it in a boolean context, but it's always better to follow what the standards say.

like image 22
gle Avatar answered Sep 22 '22 14:09

gle