How to check if a string is a valid JSON string in JavaScript without using Try/Catch
Use a JSON parser like JSON.parse
:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
I know i'm 3 years late to this question, but I felt like chiming in.
While Gumbo's solution works great, it doesn't handle a few cases where no exception is raised for JSON.parse({something that isn't JSON})
I also prefer to return the parsed JSON at the same time, so the calling code doesn't have to call JSON.parse(jsonString)
a second time.
This seems to work well for my needs:
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
};
A comment first. The question was about not using try/catch
.
If you do not mind to use it, read the answer below.
Here we just check a JSON
string using a regexp, and it will work in most cases, not all cases.
Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js
There is a regexp that check for a valid JSON, something like:
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
//the json is ok
}else{
//the json is not ok
}
EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )