例子: 下面的代码对JSON规范有效吗?
{
precision: "zip"
}
或者我应该总是使用下面的语法?(如果有,为什么?)
{
"precision": "zip"
}
我还没有在JSON规范中找到关于这方面的东西。尽管他们在例子中用引号括键。
例子: 下面的代码对JSON规范有效吗?
{
precision: "zip"
}
或者我应该总是使用下面的语法?(如果有,为什么?)
{
"precision": "zip"
}
我还没有在JSON规范中找到关于这方面的东西。尽管他们在例子中用引号括键。
当前回答
从2.2。对象
对象结构表示为围绕零个或多个名称/值对(或成员)的一对花括号。名称是字符串。
从2.5开始。字符串
字符串以引号开始和结束。
因此,我会说,根据标准:是的,您应该始终引用键(尽管一些解析器可能更宽容)
其他回答
使用字符串作为键是正确的。以下是来自RFC 4627 - JavaScript对象表示法(json)的应用程序/json媒体类型
2.2. Objects An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique. object = begin-object [ member *( value-separator member ) ] end-object member = string name-separator value [...] 2.5. Strings The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. [...] string = quotation-mark *char quotation-mark quotation-mark = %x22 ; "
在这里阅读整个RFC。
从2.2。对象
对象结构表示为围绕零个或多个名称/值对(或成员)的一对花括号。名称是字符串。
从2.5开始。字符串
字符串以引号开始和结束。
因此,我会说,根据标准:是的,您应该始终引用键(尽管一些解析器可能更宽容)
是的,引号是必须的。http://json.org/表示:
string
""
" chars "
是的,你需要引号。这是为了让它更简单,并避免为javascript保留的关键字使用另一个转义方法,例如{for:"foo"}。
Since you can put "parent.child" dotted notation and you don't have to put parent["child"] which is also valid and useful, I'd say both ways is technically acceptable. The parsers all should do both ways just fine. If your parser does not need quotes on keys then it's probably better not to put them (saves space). It makes sense to call them strings because that is what they are, and since the square brackets gives you the ability to use values for keys essentially it makes perfect sense not to. In Json you can put...
>var keyName = "someKey";
>var obj = {[keyName]:"someValue"};
>obj
Object {someKey: "someValue"}
这很好,没有问题,如果你需要一个键的值,没有引号是行不通的,所以如果它没有,你不能,所以你不会所以“你不需要对键加引号”。即使严格来说它们是字符串。逻辑和用法却不这么认为。它也没有正式输出Object {"someKey": "someValue"},在我们的例子中,从任何浏览器的控制台运行的obj。