AJAX: Check if a string is JSON?

JavascriptAjaxJsonValidation

Javascript Problem Overview


My JavaScript sometimes crashes on this line:

var json = eval('(' + this.responseText + ')');

Crashes are caused when the argument of eval() is not JSON. Is there any way to check if the string is JSON before making this call?

I don't want to use a framework - is there any way to make this work using just eval()? (There's a good reason, I promise.)

Javascript Solutions


Solution 1 - Javascript

If you include the JSON parser from json.org, you can use its parse() function and just wrap it in a try/catch, like so:

try
{
   var json = JSON.parse(this.responseText);
}
catch(e)
{
   alert('invalid json');
}

Something like that would probably do what you want.

Solution 2 - Javascript

Hers's the jQuery alternative...

try
{
  var jsonObject = jQuery.parseJSON(yourJsonString);
}
catch(e)
{
  // handle error 
}

Solution 3 - Javascript

I highly recommend you use a javascript JSON library for serializing to and from JSON. eval() is a security risk which should never be used unless you are absolutely certain that its input is sanitized and safe.

With a JSON library in place, just wrap the call to its parse() equivalent in a try/catch-block to handle non-JSON input:

try
{
  var jsonObject = JSON.parse(yourJsonString);
}
catch(e)
{
  // handle error 
}

Solution 4 - Javascript

Maybe this helps: With this code, you can get directly your data…

<!DOCTYPE html>
<html>
<body>

<h3>Open console, please, to view result!</h3>
<p id="demo"></p>

<script>
var tryJSON = function (test) {
	try {
	    JSON.parse(test);
	}
	catch(err) {
    	// maybe you need to escape this… (or not)
	    test = '"'+test.replace(/\\?"/g,'\\"')+'"';
	}
	eval('test = '+test);
	console.debug('Try json:', test);
};

// test with string…
var test = 'bonjour "mister"';
tryJSON(test);
// test with JSON…
var test = '{"fr-FR": "<p>Ceci est un texte en français !</p>","en-GB": "<p>And here, a text in english!</p>","nl-NL": "","es-ES": ""}';
tryJSON(test);
</script>

</body>
</html>

Solution 5 - Javascript

The problem with depending on the try-catch approach is that JSON.parse('123') = 123 and it will not throw an exception. Therefore, In addition to the try-catch, we need to check the type as follows:

function isJsonStr(str) {
    var parsedStr = str;
    try {
        parsedStr = JSON.parse(str);
    } catch (e) {
        return false;
    }
    return typeof parsedStr == 'object'
}

Solution 6 - Javascript

Why you can't just check what is the response? It is more more efficient.

var result;

if (response.headers['Content-Type'] === 'application/json')
    result = JSON.parse(this.responseText);
else
    result = this.responseText;

screen1

Solution 7 - Javascript

jQuery $.ajax() will add the responseJSON property to the response object, and to test if the response is JSON, you can use:

if (xhr.hasOwnProperty('responseJSON')) {}

Solution 8 - Javascript

There is a tiny library that checks JavaScript types: is.js

is.json({foo: 'bar'});
=> true

// functions are returning as false
is.json(toString);
=> false

is.not.json([]);
=> true

is.all.json({}, 1);
=> false

is.any.json({}, 2);
=> true

// 'all' and 'any' interfaces can also take array parameter
is.all.json([{}, {foo: 'bar'}]);
=> true

Actually is.js is much more then this, some honorable mentions:

var obj = document.createElement('div');
is.domNode(obj);
=> true

is.error(new Error());
=> true

is.function(toString);
=> true

is.chrome();
=> true if current browser is chrome


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick HeinerView Question on Stackoverflow
Solution 1 - JavascriptbrettkellyView Answer on Stackoverflow
Solution 2 - JavascriptRayLovelessView Answer on Stackoverflow
Solution 3 - JavascriptHåvard SView Answer on Stackoverflow
Solution 4 - JavascriptDujardin EmmanuelView Answer on Stackoverflow
Solution 5 - JavascriptHesham YassinView Answer on Stackoverflow
Solution 6 - JavascriptADM-ITView Answer on Stackoverflow
Solution 7 - JavascriptrémyView Answer on Stackoverflow
Solution 8 - Javascriptramazan polatView Answer on Stackoverflow