What is the correct way to format “true” in JSON?

前端 未结 1 1350
陌清茗
陌清茗 2021-01-07 17:34

I want to give a simple true response, but according to various JSON parsers, this is not valid JSON:

true

Ho

相关标签:
1条回答
  • 2021-01-07 18:30

    From the RFC :

    A JSON text is a serialized object or array.

      JSON-text = object / array
    

    Most parsers don't accept anything as root that isn't an object or an array. Only less strict parsers will accept that your JSON string just contains true.

    So your options are

    • to not use JSON
    • to wrap your boolean in an object : {"result":true} or an array : [true]

    Update:

    The situation changed. Newer versions of the JSON specification (see this one) explicitly accept any serialized value as root of a document:

    A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.

    It means it's now legally acceptable to use a boolean as unique value. But of course not all libraries in use are updated, which implies using anything other than an object or an array might still be problematic.

    0 讨论(0)
提交回复
热议问题