可以引用JSON数字吗? [英] Can JSON numbers be quoted?

查看:130
本文介绍了可以引用JSON数字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在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?

推荐答案

JSON 中,6是数字6 . "6"是包含数字 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必须用引号引起来,例如:

The second example is invalid, because attr must be in quotes, e.g.:

{"attr": "6"}

...是有效的,并且使用具有 string "6"的名为attr的属性定义一个对象,而:

...is valid, and defines an object with a property called attr with the string value "6", whereas:

{"attr": 6}

...有效,并定义一个对象,该对象的属性为attr,其 number 值为6,最后:

...is valid, and defines an object with a property called attr with the number value 6, and finally:

{attr: 6}

...和

{attr: "6"}

...都是无效的JSON,因为属性名称必须用双引号引起来.

...are both invalid JSON because property names must be in double quotes.

如果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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆