简体   繁体   English

JSON和JavaScript对象文字中的有效名称之间的区别

[英]Difference between valid names in JSON and JavaScript object literals

I have a JSON-formatted document like so: 我有一个JSON格式的文档,如下所示:

{
    "the-field": "something",
    // etc
}

When I call foo = JSON.parse() it spits out an object literal with a field foo.the-field , but when I try console.log(foo.the-field) I'm told that it's not proper formatting for a JavaScript variable. 当我调用foo = JSON.parse()它会抛出带有字段foo.the-field的对象文字,但是当我尝试console.log(foo.the-field)我被告知对于a而言,格式不正确JavaScript变量。 What gives? 是什么赋予了?

You need to use the bracket notation instead of dot notation as the member operator here 您需要在此处使用方括号符号代替点符号作为成员运算符

foo["the-field"]

From Docs 从文档

If you are using dot notation then 如果您使用点符号,则

property must be a valid JavaScript identifier, ie a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. 属性必须是有效的JavaScript标识符,即,一个字母数字字符序列,还包括下划线(“ _”)和美元符号(“ $”),它们不能以数字开头。 For example, object.$1 is valid, while object.1 is not. 例如,object。$ 1有效,而object.1无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM