格式化“真"格式的正确方法是什么?在JSON中? [英] What is the correct way to format "true" in JSON?
问题描述
我想给出一个简单的true
响应,但是根据各种 JSON 解析器,这不是有效的JSON:
I want to give a simple true
response, but according to various JSON parsers, this is not valid JSON:
true
但是,无论是编码还是解码,PHP和Javascript的行为都像"true"一样,对于true
而言确实是有效的JSON:
However, PHP and Javascript act like "true" is indeed valid JSON for true
, both when encoding and when decoding:
PHP-
echo json_encode( true ); // outputs: true
echo json_decode( true ); // outputs: 1
echo gettype(json_decode( true )); // outputs: boolean
jQuery-
JSON.stringify( true ); // outputs: true
jQuery.parseJSON( true ); // outputs: true
typeof jQuery.parseJSON( true ); // outputs: boolean
那么发送格式为JSON的true
响应的正确方法是什么?验证者都错了吗?
So what is the correct way to send a true
response formatted as JSON? Are the validators all wrong?
推荐答案
来自 RFC :
JSON文本是序列化的对象或数组.
A JSON text is a serialized object or array.
JSON-text = object / array
大多数解析器不接受任何不是对象或数组的东西作为根.只有不太严格的解析器会接受您的JSON字符串仅包含true
.
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
.
所以您的选择是
- 不使用JSON
- 将布尔值包装在对象:
{"result":true}
或数组:[true]
中
- to not use JSON
- to wrap your boolean in an object :
{"result":true}
or an array :[true]
更新:
情况发生了变化. JSON规范的较新版本(请参见此)明确接受任何序列化的值作为文档的根:
The situation changed. Newer versions of the JSON specification (see this one) explicitly accept any serialized value as root of a document:
JSON文本是序列化的值.请注意,某些先前的 JSON规范将JSON文本限制为对象或 大批.仅生成对象或数组的实现,其中 JSON文本将在所有意义上都可互操作 实现将接受这些作为符合条件的JSON文本.
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.
这篇关于格式化“真"格式的正确方法是什么?在JSON中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!