在 JSON 中格式化“true”的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19435906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the correct way to format "true" in JSON?
提问by brentonstrine
I want to give a simple trueresponse, but according to variousJSONparsers, this is notvalid JSON:
我想给出一个简单的true响应,但根据各种JSON解析器,这不是有效的 JSON:
true
However, PHP and Javascript act like "true" is indeed valid JSON for true, both when encoding and when decoding:
但是,true在编码和解码时,PHP 和 Javascript 就像 "true" 确实是有效的 JSON :
PHP-
PHP-
echo json_encode( true ); // outputs: true
echo json_decode( true ); // outputs: 1
echo gettype(json_decode( true )); // outputs: boolean
jQuery-
jQuery-
JSON.stringify( true ); // outputs: true
jQuery.parseJSON( true ); // outputs: true
typeof jQuery.parseJSON( true ); // outputs: boolean
So what is the correct way to send a trueresponse formatted as JSON? Are the validators all wrong?
那么发送trueJSON 格式的响应的正确方法是什么?验证器都错了吗?
采纳答案by Denys Séguret
From the RFC:
从RFC:
A JSON text is a serialized object or array.
JSON-text = object / array
JSON 文本是序列化的对象或数组。
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.
大多数解析器不接受任何不是对象或数组的根。只有不太严格的解析器才会接受您的 JSON 字符串只包含true.
So your options are
所以你的选择是
- to not use JSON
- to wrap your boolean in an object :
{"result":true}or an array :[true]
- 不使用 JSON
- 将您的布尔值包装在一个对象中:
{"result":true}或一个数组:[true]
Update:
更新:
The situation changed. Newer versions of the JSON specification (see this one) explicitly accept any serialized value as root of a document:
情况发生了变化。较新版本的 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.
JSON 文本是一个序列化值。请注意,某些先前的 JSON 规范将 JSON 文本限制为对象或数组。仅生成需要 JSON 文本的对象或数组的实现将是可互操作的,因为所有实现都将接受这些作为一致的 JSON 文本。
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.
这意味着现在使用布尔值作为唯一值在法律上是可以接受的。但当然并不是所有使用的库都被更新,这意味着使用对象或数组以外的任何东西可能仍然有问题。

