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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With