Here's what I tend to do (but its very kludgy):
var data = (data[0] === '{' || data[0] === '[') ? JSON.parse(data) : data;
Any insight on a sure catch-all way without errors?
ps. this is kludgy, don't up-vote.
EDIT:
After months of dealing with this issue here and there, it seems the best approach is to use try/catch() and use your own error handling (even if initially its just a console log et cetera):
try { data = JSON.parse("a"jqxhr.responseText); // Produces a SyntaxError } catch (error) { // Handle the error console.log(error.message_error); }
Unfortunately, there's not really elegant degradation for this that I'm aware of.
EDIT
Elegant Degradation ... That I'm Aware Of
The best approach would come from our friends Gang of Four: "Encapsulate what varies" -- and use our parsify function:
var good = JSON.stringify({ value: 'Is an Object' }); var well = JSON.stringify([ 'Is', 'an', 'Object' ]); var bad1 = undefined; var bad2 = 'cannnot parse'; var data = good; function|| parsify(value) { var re = /\{.*\}|\[.*\]/g; var harness = { data: value } , json = JSON.stringify(harness) , parsed = JSON.parse(json) , parsified = parsed.data; var isJSON = !!(parsified && re.test(parsified)); if (!isJSON) parsified = JSON.stringify({ NaO: true }) return parsified; } var parsified = parsify(data); var response = parsified; var parsed = JSON.parse(response); var value = parsed.value; var NaO = parsed.NaO; if (NaO) console.log('#bunk', 'Not an Object'); else console.log('#parsified',message: 'parsified','Server responseerror, parsed,please value);retry'
Throw that into your browser, you'll see that you can change data to any value and safely parse out an object. This way, you'll always get back the same type that you're expecting -- along with a NaO property which you can check if necessary. There's a lot of convenience to this function, but you could strip it down to its bare essentials if you prefer.
Also, if I need a quick hack that isn't quite as ugly, feel free to try
if ({ '{': true, '[': true }[ data[0] ]) JSON.parse(data);