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?
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 ).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With