Skip to content

Is String JSON or XML?

Last weekend I spent some time updating a web application I wrote so that data is passed between server and client with JSON instead of XML. The catch is that it only was going to use JSON in some cases, and there are lots of database records that already have XML in them. So I needed a way for the browser to know whether a string was XML or JSON.

Not sure this is the best solution, but it seems to be working. I’m just assuming that if the string starts with a < it’s XML and if not it’s JSON.

var theString = "some unknown value";
if (theString.trim().startsWith('<')) {
   // It's probably XML
}
else {
   // It's probably JSON
}

I did cheat a bit and am working under the assumption that it’s either XML or JSON and there isn’t a third option. I probably need some sort of validation for that, but we’re going to go with it’s working well enough for now.

There is a bit of irony here though in that I was using jQuery plugin called xml2json to convert the XML to JSON anyway, so I really should have saved that step from the beginning and none of this would have been necessary.

Published inCoding

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *