snippetjavascriptCritical
How to check if a string is a valid JSON string?
Viewed 0 times
howcheckvalidstringjson
Problem
isJsonString('{ "Id": 1, "Name": "Coke" }')should be
true andisJsonString('foo')
isJsonString('foo')should be
false.I'm looking for a solution that doesn't use
try/catch because I have my debugger set to "break on all errors" and that causes it to break on invalid JSON strings.Solution
A comment first. The question was about not using
If you do not mind to use it, read the answer below.
Here we just check a
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:
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 )
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 )
Code Snippets
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
}Context
Stack Overflow Q#3710204, score: 214
Revisions (0)
No revisions yet.