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?
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?
Share Improve this question edited Aug 16, 2016 at 10:37 rdubya 2,9161 gold badge17 silver badges21 bronze badges asked Aug 16, 2016 at 10:14 Tom TaylorTom Taylor 3,5802 gold badges41 silver badges72 bronze badges 3- what do you mean by boolean type formats? – Daniel A. White Commented Aug 16, 2016 at 10:16
-
He means
isJSON(false)
returnstrue
. – Jeremy Thille Commented Aug 16, 2016 at 10:17 - Yeah you were right Jeremy Thille – Tom Taylor Commented Aug 16, 2016 at 11:03
2 Answers
Reset to default 8To 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;
}
}
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;
}