11

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 ?

1 Answer 1

31

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.