I’m working in an application that sends to me a XML so I can work with the data in it. But now the application will send not only a XML, but also a JSON, depending on other variables.
Is there any way that I can verify if what has been sent is a JSON? Something equivalent to typeof or instanceof that will tell me that string is a JSON?
Edit: I’m giving maintenance in this application that has been built using a very, very bad programmed framework. Right now my “data” is the return of a function and I’m unable to get the Content-Type without refactoring good part of the framework – what would take me months – and I don’t have this time right now.
Right now:
ajax.request('POST',function(data){
xml = loadXML(data); // It's always a XML, so I simply load it.
...
..
})
What I need:
ajax.request('POST',function(data){
if(valueCanBeJSON(data)){ // It's not always a XML. How can I do this verification?
json = eval('('+data+')');
}else{
xml = loadXML(data);
...
..
}
})
As @Gumbo commented, you can check the
Content-TypeHTTP response header field. Alternately, you could try to parse it — though don’t useeval(). UseJSON.parse(). If you’re using jQuery,$.parseJSON()or just$.ajax()(without specifying thedata-type) will also work.