Javascript 从JSON调用变量

Javascript 从JSON调用变量,javascript,arrays,json,node.js,Javascript,Arrays,Json,Node.js,我从XML文件中读取数据并将其存储在变量XML中 稍后,我将其转换为JSON格式,并将其保存在变量JSON中 以下是JSON: { 'maven2-moduleset': { '$': { plugin: 'maven-plugin@2.15.1' }, actions: [''], description: [''], keepDependencies: ['false'], properties: [ [Object

我从XML文件中读取数据并将其存储在变量
XML

稍后,我将其转换为JSON格式,并将其保存在变量
JSON

以下是JSON:

{
  'maven2-moduleset': {
    '$': {
      plugin: 'maven-plugin@2.15.1'
    },
    actions: [''],
    description: [''],
    keepDependencies: ['false'],
    properties: [
      [Object]
    ],
    scm: [
      [Object]
    ]
  }
}
当我尝试太多的时候

console.log(jason.maven2-moduleset.$.scm)
它抛出了以下错误

events.js:154
      throw er; // Unhandled 'error' event
      ^

ReferenceError: moduleset is not defined
    at /NodeJS/configxml/configxml.js:20:62
    at Parser.<anonymous> (/NodeJS/configxml/node_modules/xml2js/lib/xml2js.js:489:18)
    at emitOne (events.js:90:13)
    at Parser.emit (events.js:182:7)
    at Object.onclosetag (/NodeJS/configxml/node_modules/xml2js/lib/xml2js.js:447:26)
    at emit (/NodeJS/configxml/node_modules/sax/lib/sax.js:640:35)
    at emitNode (/NodeJS/configxml/node_modules/sax/lib/sax.js:645:5)
    at closeTag (/NodeJS/configxml/node_modules/sax/lib/sax.js:905:7)
    at Object.write (/NodeJS/configxml/node_modules/sax/lib/sax.js:1452:13)
    at Parser.exports.Parser.Parser.parseString (/NodeJS/configxml/node_modules/xml2js/lib/xml2js.js:508:31)
events.js:154
投掷者;//未处理的“错误”事件
^
ReferenceError:未定义moduleset
at/NodeJS/configxml/configxml.js:20:62
在解析器处。(/NodeJS/configxml/node_modules/xml2js/lib/xml2js.js:489:18)
在emitOne(events.js:90:13)
在Parser.emit(events.js:182:7)
在Object.onclosetag(/NodeJS/configxml/node_modules/xml2js/lib/xml2js.js:447:26)
在发出时(/NodeJS/configxml/node_modules/sax/lib/sax.js:640:35)
在emitNode(/NodeJS/configxml/node_modules/sax/lib/sax.js:645:5)
在closeTag(/NodeJS/configxml/node_modules/sax/lib/sax.js:905:7)
在Object.write(/NodeJS/configxml/node_modules/sax/lib/sax.js:1452:13)
位于Parser.exports.Parser.Parser.parseString(/NodeJS/configxml/node_modules/xml2js/lib/xml2js.js:508:31)

我想在“scm”中获取数据,不知道哪里做错了。可以告诉我如何在scm对象中显示数据。

问题是您试图使用带有无效字符(破折号)的点表示法。要解决这个问题,应该使用数组表示法。例如,
jason['maven2-moduleset']['$']['scm']
无论以哪种方式访问相同的值,格式都略有不同

JavaScript标识符必须以字母、下划线(_)或美元符号($)开头;后续字符也可以是数字(0-9)。因为JavaScript是区分大小写的,所以字母包括字符“A”到“Z”(大写)和字符“A”到“Z”(小写)。


这里有两个问题,但不用担心,因为这两个问题都很容易解决

第1期-不能将点符号与带符号的键一起使用

相反,您必须使用
[]
,将密钥名称作为字符串,例如:

无效:
console.log(jason.maven2模块集)

有效:
console.log(jason['maven2-moduleset'])


问题2-
scm
不是
$
的属性

$
只有一个属性,它是
plugin


解决方案


这将起作用:
console.log(jason['maven2-moduleset'].scm)
scm
不是
$
上的字段。根据您的对象文字,它是它的兄弟。试试
console.log(jason['maven2-moduleset'].scm)
看看合理缩进有多重要?即使您使用的是“未格式化”JSON,您仍然可以对其进行美化,以提高其易读性。本来打算对此进行升级,但投票数不足:保留此评论以便我以后可以升级
scm
不在
$
项下。不过,您的右侧,我保留此评论是为了更真实地满足问题中的请求。用我写的东西,你会得到未定义的,但你不会得到一个错误。为什么点符号无效?你能简要说明一下吗?只有当你在键名中有符号时,它才无效,在这种情况下,这是因为
-
中的
maven2 moduleset
也是减号运算符。