Calling variable from JSON

时间:2017-04-24 17:27:07

标签: javascript arrays json node.js

I read data from an XML file and store it in the variable xml.

Later I convert this into JSON format and save it in the variable json.

Following is JSON:

{
  'maven2-moduleset': {
    '$': {
      plugin: 'maven-plugin@2.15.1'
    },
    actions: [''],
    description: [''],
    keepDependencies: ['false'],
    properties: [
      [Object]
    ],
    scm: [
      [Object]
    ]
  }
}

when I'm trying too access

console.log(jason.maven2-moduleset.$.scm)

it's throwing following error

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)

I want to get data in 'scm' , Don't know where I'm doing wrong. Could tell me how to display data in scm object.

2 个答案:

答案 0 :(得分:0)

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

问题1 - 您不能将带有符号的点符号用于符号

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

无效:console.log(jason.maven2-moduleset)

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

问题2 - scm不属于$ 的属性

$只有一个属性,它是plugin

<强>解决方案

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

答案 1 :(得分:-1)

The problem is that you are trying to use dot notation with an invalid character (the dash). To fix this you should use array notation. EX. jason['maven2-moduleset']['$']['scm'] either way it accesses the same values, it's just a slightly different format

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables