jsonboolean

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


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?


Solution

  • Short answer, yes, your second example 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.