可以引用 JSON 数字吗? [英] Can JSON numbers be quoted?
问题描述
JSON 数字周围可以有引号吗?在大多数搜索链接中,数字似乎并不需要"引号.但是,解析器是否应该同时接受 "attr" : 6
和 "attr" : "6"
?
Can there be quotes around JSON numbers? In most of the search links, it seems that numbers do not "require" quotes. But, should the parsers accept both "attr" : 6
and "attr" : "6"
?
如果 MyParser
有一个方法 getInt
来获取给定键的数字,MyParser.getInt("attr")
应该返回 6
在这两种情况下,还是在后一种情况下抛出异常?
If MyParser
has a method getInt
to get a number given the key, should MyParser.getInt("attr")
return 6
in both cases, or throw an exception in the latter case?
推荐答案
In JSON, 6
是数字六.6"
是一个包含 digit 6
的字符串.所以问题的答案可以引用 json 数字吗?" 基本上是不,"因为如果你把它们放在引号中,它们就不再是数字了.
In JSON, 6
is the number six. "6"
is a string containing the digit 6
. So the answer to the question "Can json numbers be quoted?" is basically "no," because if you put them in quotes, they're not numbers anymore.
但是,如果解析器同时接受 "attr": 6
和 "attr";:6"
?
But, should the parsers accept both
"attr" : 6
and"attr" : "6"
?
是的,但它们定义了不同的东西.第一个定义了一个 attr
属性,其值为 6
(一个数字).第二个定义了一个 attr
属性,其值为 6"
(一个包含单个数字的字符串).
Yes, but they define different things. The first defines an attr
property with the value 6
(a number). The second defines an attr
property with the value "6"
(a string containing a single digit).
(最初询问的问题是关于 attr: 6"
,这是无效的,因为属性名称在 JSON 中必须用双引号引起来.)
(The question originally asked about attr: "6"
, which is invalid because property names must be in double quotes in JSON.)
如果 MyParser 有一个方法 getInt 来获取给定键的数字,那么 MyParser.getInt(attr") 在这两种情况下都应该返回 6 还是在后一种情况下抛出异常?
If MyParser has a method getInt to get a number given the key, should MyParser.getInt("attr") return 6 in both the cases or throw an exception in the latter case?
这是提供解析器的人的设计决定,基本上是在 getInt
严格(如果您在 "attr" 上尝试时抛出异常:"6"
) 或松散的(将 6"
强制转换为 6
并返回).JavaScript 通常是松散的,因此可能存在松散的争论;相反,JavaScript 松散的事实有时会导致麻烦,这可能是严格的一个论据.
That's a design decision for the person providing the parser, basically the choice between getInt
being strict (throwing an exception if you try it on "attr": "6"
) or loose (coercing "6"
to 6
and returning that). JavaScript is usually loose, and so there could be an argument for being loose; conversely, the fact that JavaScript is loose sometimes causes trouble, which could be an argument for being strict.
这篇关于可以引用 JSON 数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!