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,916
  • 1
  • 16
  • 20
Tom Taylor
  • 3,344
  • 2
  • 38
  • 63

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,448
  • 2
  • 15
  • 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
  • 26,047
  • 12
  • 43
  • 63