Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml2js - xml tag values converted to array of jsons

Tags:

json

xml

xml2js

I am using the following code to convert xml to json :-

var parseString = require('xml2js').parseString;

var xml = "<root><param_name>Hello</param_name><param_entry> xml2js!  </param_entry> </root>";

parseString(xml, {trim: true},function(err,result){
console.dir(JSON.stringify(result));
});

It is returning the following result -

{  
   "root":{  
  "param_name":[  
     "Hello"
  ],
  "param_entry":[  
     " xml2js!"
  ]
     }
   }

It is returning value of as collection of objects i.e. as "param_name":[
"Hello" ].

But I want it as a simple key and value form. That is my resultant JSON should look like -

{  
   "root":{  
      "param_name":  
         "Hello"
      ,
      "param_entry":
         " xml2js!"

   }
}

What is it that is going wrong here ?

like image 206
Aarushi Mishra Avatar asked Mar 15 '17 08:03

Aarushi Mishra


1 Answers

The solution is to - use the {explicitArray:false} option for the parser as follows:

var xml2js = require('xml2js');

var parser = new xml2js.Parser({explicitArray : false});
var xml = "<root><param_name>Hello</param_name><param_entry> xml2js!   </param_entry> </root>";

parser.parseString(xml,function(err,result){
    console.dir(JSON.stringify(result));
});

As per npm doc of xml2js - by default it is set to "true" - so all child nodes are put in an array. By setting this as "false" - child nodes are added into an array if they are present multiple times. i.e multiple tags are present.

like image 96
Aarushi Mishra Avatar answered Oct 16 '22 00:10

Aarushi Mishra