AJAX: Check if the string is JSON?

My JavaScript sometimes crashes on this line:

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

Failures occur when the eval() argument is not JSON. Is there a way to check if the string is JSON before making this call?

I do not want to use the framework - is there a way to make this work using only eval() ? (There's a good reason, I promise.)

+82
json javascript ajax validation
Feb 22 '10 at 19:46
source share
9 answers

If you enable the parser

+154
Feb 22 '10 at 19:50
source share

Installs jQuery alternative ...

 try { var jsonObject = jQuery.parseJSON(yourJsonString); } catch(e) { // handle error } 
+21
Dec 27
source share

I highly recommend you use javascript JSON library to serialize to and from JSON. eval() is a security risk that should never be used if you are absolutely not sure that its input into sanitation and security.

Using the JSON library, simply wrap the call with the parse() equivalent in try / catch-block to handle non-JSON input:

 try { var jsonObject = JSON.parse(yourJsonString); } catch(e) { // handle error } 
+14
Feb 22 '10 at 19:50
source share

Promise instead of Try-catch :

 npm install is-json-promise ; //for NodeJS environment. 

OR

 String.IsJSON = (candidate) => new Promise( (resolve, reject) => resolve(JSON.parse(candidate)) ) ; 



Use cases:

 String.IsJSON(`iam here`) .then((object) => console.info(object)) .catch((error) => alert('Waww, i cannot be JSON')) ; // promise will run catch 

or

 String.IsJSON(`{"welcome":"Hello"}`) .then((object) => console.info(object)) // promise will run "then" .catch((error) => alert('Waww, i cannot be JSON')) ; 
+8
Nov 21 '16 at 17:59
source share

Maybe this will help: With this code you can get your data directly ...

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

+2
Oct 24 '18 at 10:42
source share

The problem with the dependency on the try-catch approach is that JSON.parse('123') = 123 will not throw an exception. Therefore, in addition to 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' } 
0
Jul 30 '18 at 11:33
source share

Below is a function you can try:

 String.prototype.isJson = function () { try { JSON.parse(this.toString()); return true; } catch (ex) { return false; } }; 
0
Sep 28 '18 at 8:04
source share

There is a small library that checks for 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 than some, some of which deserve mention:

 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 
0
Feb 23 '19 at 0:20
source share

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

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

screen1

0
Aug 29 '19 at 21:45
source share



All Articles