Adil Waqar Adil Waqar - 5 months ago 13
JSON Question

Extracting JSON from string

I am getting a string from server and want to extract Json string from it
here is the string

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">
[{"isAssigned": false,"Name": "c:\\inetpub\\wwwroot\\XLEZ\\CLIENT","LastModified": ""},
{"isAssigned": true,"Name": "\\mokuji.html","LastModified": "20140806 165709"},
{"isAssigned": false,"Name": "\\result.html",{"LastModified": "20131002 235302"}]
</string>


I am not being able to figure out how to do it...
Here is JSFiddle

Answer

Based on this via XML <-> JSON conversion in Javascript

I did this:

Live Demo

No error handling

function parseXml(xml) {
  var dom = null;
  if (window.DOMParser) {
    try {
        dom = (new DOMParser()).parseFromString(xml, "text/xml");
    } catch (e) {
        dom = null;
    }
  } else if (window.ActiveXObject) {
    try {
        dom = new ActiveXObject('Microsoft.XMLDOM');
        dom.async = false;
        if (!dom.loadXML(xml)) // parse error ..

        window.alert(dom.parseError.reason + dom.parseError.srcText);
    } catch (e) {
        dom = null;
    }
  } else alert("cannot parse xml string!");
  return dom;
}


function extractJson() {
  var xml = '<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">[ {"x":"y"},{"a":"b"}]</string>';
  var json = JSON.parse(parseXml(xml).firstChild.textContent);
  console.log(json)
}