1

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?

rdubya
  • 2,906
  • 1
  • 14
  • 20
Tom Taylor
  • 2,887
  • 2
  • 34
  • 55

2 Answers2

8

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;
    }
}
Simone Poggi
  • 1,348
  • 2
  • 14
  • 34
2

Your function works, just add a boolean check :

function isJSON(str) {

    if(typeof(str) === "boolean"){ return false; } // or if(typeof(str) !== "string")

    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
Jeremy Thille
  • 25,196
  • 9
  • 41
  • 59