JSON 值 1 或 0 - int 或 boolean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6542018/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:54:47  来源:igfitidea点击:

JSON values 1 or 0 - int or boolean

jsonintegerboolean

提问by Phill Pafford

Does JSON treat these all the same? Or are they a mix of Integers and booleans?

JSON 是否对这些都一视同仁?或者它们是整数和布尔值的混合体?

var data =
{
    "zero" : 0,
    "one" : 1,
    "false" : 0,
    "true" : 1,
    "0" : false,
    "1" : true
}

回答by Rob Agar

The values trueand falseare actual boolean values, the rest are integers. See http://json.org/for more.

truefalse是实际的布尔值,其余的是整数。有关更多信息,请参阅http://json.org/

回答by SLaks

JSON is a format for transferring data.
It has no notion of equality.

JSON 是一种传输数据的格式。
它没有平等的概念。

JSON parserstreat booleans and numbers as distinct types.

JSON解析器将布尔值和数字视为不同的类型。

回答by Hieu Vo

I prefer using 0/1 instead of true/false, because 0/1 consume only 1 byte while true/false consume 4/5 bytes.

我更喜欢使用 0/1 而不是 true/false,因为 0/1 只消耗 1 个字节,而 true/false 消耗 4/5 个字节。

回答by StaxMan

As mentioned, at JSON level, 0 and false are not the same; data types are number versus boolean. But JSON processing libraries can choose to do conversions; especially on languages/platforms that do not have native boolean type, for example. In that case, another representation may be used (empty string or 0 for false).

如前所述,在 JSON 级别,0 和 false 是不一样的;数据类型是数字与布尔值。但是JSON处理库可以选择做转换;例如,尤其是在没有原生布尔类型的语言/平台上。在这种情况下,可以使用另一种表示形式(空字符串或 0 表示假)。

Further, it is also possible that processing libraries can coerce types: such that if a boolean value is expected, certain number/string values (or JSON 'null' token) can be accepted instead. This is fairly common, due to differences on data type choices on different languages.

此外,处理库也可以强制类型:如果需要布尔值,则可以接受某些数字/字符串值(或 JSON 'null' 标记)。这是相当普遍的,因为不同语言的数据类型选择存在差异。