0

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

AddyProg
  • 2,960
  • 13
  • 59
  • 110
  • You could try [`$.parseXML`](http://api.jquery.com/jquery.parsexml/) and then get the string `string` element in the XML. – Danny Aug 08 '14 at 13:52
  • 4
    Your example code doesn't contain valid JSON. – Quentin Aug 08 '14 at 13:53
  • @Quentin I know its just for reference actual data has valid json but its in those xml tags i want to get rid of these tags – AddyProg Aug 08 '14 at 13:56
  • 3
    @AdilWaqar — If it contained valid JSON then people could fork it to test and demo code without having to fix your sample data first. – Quentin Aug 08 '14 at 13:57
  • @Quentin example edited .. now it shows actual data – AddyProg Aug 08 '14 at 14:05

5 Answers5

3

Based on this via Convert XML to JSON (and back) using 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)
}
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    This solution provides the best options for parsing XML in multiple browser environments, as well as the best DOM navigation practices. – JAAulde Aug 08 '14 at 14:09
  • I guess I should also have posted the jQuery I did not post because it was not tagged jQuery :/ – mplungjan Aug 08 '14 at 14:24
2

If you are not opposed to using jQuery, it handles traversing and extracting data from XML strings just as well as HTML strings.

You can pull the JSON string like so

    // Get JSON string out
    var extractedJson = $(jsonData).text();

    // If you need it as an object
    var extractedJsonAsObject = $.parseJSON(extractedJson);

Here is a working example of your Fiddle:

http://plnkr.co/edit/nfnjreyfv0adIZ6Ue1Ox?p=preview

davidmdem
  • 3,763
  • 2
  • 30
  • 33
  • 1
    This assumes that the XML will never contain anything other than a single element with JSON, and no whitespace. I suspect the OP's example was quite simple for the sake of brevity, and that the actual XML in the wild may be more complex. – JAAulde Aug 08 '14 at 14:11
  • Fair enough. I assumed that they could pick it up from there. CSS selectors for traversing the XML document also work the same as they do traversing HTML. – davidmdem Aug 08 '14 at 14:12
  • Yeah, I hear ya. I just wanted the OP to understand he may need to do a little more in case it wasn't obvious to him. – JAAulde Aug 08 '14 at 14:14
1

You could simply parse the XML and get its content

function extractJson()
{

var jsonData = '<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">[ {'sone': 'json'},{'some': 'json2'}]</string>';
    var parser = new DOMParser();
 var xmlDoc = parser.parseFromString(jsonData,"text/xml");
console.log(xmlDoc.getElementsByTagName('string')[0].innerHTML);    
}
extractJson();

Note: Internet Explorer uses the loadXML() method to parse an XML string, while other browsers use the DOMParser object.

Pal Singh
  • 1,964
  • 1
  • 14
  • 29
0

Here is a GIST that does the job.

The code is in kotlin but can be easily translated into any language.

N Jay
  • 1,774
  • 1
  • 17
  • 36
-2

Assuming Json doesn't contains tags, you can just replace all xml tags with empty string (ie remove them) like this:

function extractJson(){
    var jsonData = '<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">[ {sonejson},{some json2}]</string>';
    var extractdJson = jsonData.replace(/\<[^\>]+\>/gi,''); // extracted jason fron jsonData 
    alert(extractdJson);    
}

Hope this helps

webNeat
  • 2,768
  • 1
  • 20
  • 22
  • 1
    You should really avoid using anything but an actual parser to work with, and extract data from, markup. – JAAulde Aug 08 '14 at 14:08
  • If JSON will not contain any xml tags, then this will be more simple and fast then using a parser. – webNeat Aug 08 '14 at 14:10
  • I disagree wholeheartedly. Furthermore, if your solution requires caveats and conditions to be useful, you can be sure those caveats and conditions will be violated in the wild. – JAAulde Aug 08 '14 at 14:13
  • The solution should be general or it's not useful yeah – webNeat Aug 08 '14 at 14:18