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

5
  • You could try $.parseXML and then get the string string element in the XML. Commented Aug 8, 2014 at 13:52
  • 4
    Your example code doesn't contain valid JSON. Commented Aug 8, 2014 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 Commented Aug 8, 2014 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. Commented Aug 8, 2014 at 13:57
  • @Quentin example edited .. now it shows actual data Commented Aug 8, 2014 at 14:05

4 Answers 4

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

This solution provides the best options for parsing XML in multiple browser environments, as well as the best DOM navigation practices.
I guess I should also have posted the jQuery I did not post because it was not tagged jQuery :/
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

3 Comments

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.
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.
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.
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.

Comments

-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

4 Comments

You should really avoid using anything but an actual parser to work with, and extract data from, markup.
If JSON will not contain any xml tags, then this will be more simple and fast then using a parser.
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.
The solution should be general or it's not useful yeah

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.