比如:
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
解决方案不应包含try/catch.我们中的一些人打开"在所有错误上中断",他们不喜欢调试器中断那些无效的JSON字符串.
比如:
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
解决方案不应包含try/catch.我们中的一些人打开"在所有错误上中断",他们不喜欢调试器中断那些无效的JSON字符串.
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.
看一下450/https://github.com/douglascrockford/JSON-js/blob/master/json2.js这条线
有一个regexp可以判断有效的JSON,比如:
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:json2的新版本.js进行了比上面更高级的解析,但仍然基于regexp替换(从comment of @Mrchief开始)