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