Home > Mobile >  javascript how to convert xml to json without using any custom libraries
javascript how to convert xml to json without using any custom libraries

Time:03-10

I want to convert xml to json without using any custom libray or framework like xml2json.

below is the xml

<m:properties>
        <d:ContactOrigin>SAP_S4_BUPA</d:ContactOrigin>
        <d:ContactID>DE00000042</d:ContactID>
        <d:ValidationStatus/>
        <d:ValidationStatusName>Anonymous</d:ValidationStatusName>
        <d:IsEndOfPurposeBlocked>false</d:IsEndOfPurposeBlocked>
</m:properties>

output json should be like below..

var json = {
    "ContactOrigin": "SAP_S4_BUPA",
    "ContactID": "DE00000042",
    "ValidationStatus": "",
    "ValidationStatusName": "Anonymous",
    "IsEndOfPurposeBlocked": false
}

I googled about this issue, but everywhere i got solution using custom library.

Can someone help me to convert xml to json without using any framework

CodePudding user response:

your xml is not valid, so I needed to fix it at first

xml = xml.replaceAll("m:","").replaceAll("d:","");

var parser = new DOMParser();
xmlDoc = parser.parseFromString(xml,"text/xml");
var tags = xmlDoc.getElementsByTagName("properties");
var details = tags[0].children;

var jsonObj = {};
for (index = 0; index < details.length; index  ) 
  jsonObj[details[index].tagName] = details[index].textContent;

var json=JSON.stringify(jsonObj,null,4);

input xml

     <m:properties>
        <d:ContactOrigin>SAP_S4_BUPA</d:ContactOrigin>
        <d:ContactID>DE00000042</d:ContactID>
        <d:ValidationStatus/>
        <d:ValidationStatusName>Anonymous</d:ValidationStatusName>
        <d:IsEndOfPurposeBlocked>false</d:IsEndOfPurposeBlocked>
    </m:properties>

output json

{
  "ContactOrigin": "SAP_S4_BUPA",
  "ContactID": "DE00000042",
  "ValidationStatus": null,
  "ValidationStatusName": "Anonymous",
  "IsEndOfPurposeBlocked": "false"
}

CodePudding user response:

I acheived my requirement using below approach..

function xml2json(xml) {
  try {
    var obj = {};
    if (xml.children.length > 0) {
      for (var i = 0; i < xml.children.length; i  ) {
        var item = xml.children.item(i);
        var nodeName = item.nodeName;

        if (typeof (obj[nodeName]) == "undefined") {
          obj[nodeName] = xml2json(item);
        } else {
          if (typeof (obj[nodeName].push) == "undefined") {
            var old = obj[nodeName];

            obj[nodeName] = [];
            obj[nodeName].push(old);
          }
          obj[nodeName].push(xml2json(item));
        }
      }
    } else {
      obj = xml.textContent;
    }
    return obj;
  } catch (e) {
      console.log(e.message);
  }
}

Im calling above function with my xml like below..

var jsonVal = xml2json(result.documentElement);
  • Related