VicSan
VicSan

Reputation: 119

Cannot access json values after converting from xml using xml-js parser

I parse the xml using the following code

var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});

The result throws the following JSON

{
    "declaration": {
        "attributes": {
            "version": "1.0",
            "encoding": "utf-8"
        }
    }
}

However if i try accesing "declaration" using result["declaration"]the console returns undefined

Should i use another parser or is there something wrong with getting the value.

Upvotes: 0

Views: 592

Answers (2)

hong4rc
hong4rc

Reputation: 4113

Please use xml2js instead of xml2json if you want it return object.

result = convert.xml2js(xml, options);    // to convert xml text to javascript object
result = convert.xml2json(xml, options);  // to convert xml text to json text

Upvotes: 1

shaochuancs
shaochuancs

Reputation: 16246

The data type of result is String, not JavaScript object. That is, the convert.xml2json(xml, { spaces: 4}); statement will return a JSON String, not JS object.

To access declaration, you need to parse the JSON string to object:

var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});

result = JSON.parse(result);

Upvotes: 1

Related Questions