且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不使用Try / Catch的情况下检查字符串是否是JavaScript中的有效JSON字符串

更新时间:2023-11-26 11:16:28

首先发表评论。问题是关于不使用 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 ,类似于:

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

}

编辑:新版本的json2.js进行了比上面更高级的解析,但仍然基于regexp替换(f @Mrchief评论

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 )