Rabbit Rabbit - 3 months ago 13
jQuery Question

How to check if a json string is valid or not in JavaScript or Jquery?

Have tried :

function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}


To check weather a string is json or not. It returns true for boolean type formats.

Is there any possible way to identify a valid json string in Java Script or in JQuery?

Answer

To assure you have a valid json you must have a string first

function isJSON(str) {

    if( typeof( str ) !== 'string' ) { 
        return false;
    }
    try {
        JSON.parse(str);
        return true;
    } catch (e) {
        return false;
    }
}
Comments