如何在不使用 Try/Catch 的情况下检查字符串是否为 JavaScript 中的有效 JSON 字符串 [英] How to check if a string is a valid JSON string in JavaScript without using Try/Catch
问题描述
类似于:
var jsonString = '{ "Id": 1, "Name": "Coke" }';//应该是真的IsJsonString(jsonString);//应该是假的IsJsonString("foo");IsJsonString("foo")
解决方案不应包含 try/catch.我们中的一些人打开了中断所有错误",他们不喜欢调试器中断那些无效的 JSON 字符串.
先评论.问题是关于不使用 try/catch
.
如果您不介意使用它,请阅读下面的答案.这里我们只是使用正则表达式检查一个 JSON
字符串,它适用于大多数情况,而不是所有情况.
查看 https://github 中的 450 行.com/douglascrockford/JSON-js/blob/master/json2.js
有一个检查有效 JSON 的正则表达式,例如:
if (/^[],:{}s]*$/.test(text.replace(/\["\/bfnrtu]/g, '@').替换(/"[^"\
]*"|true|false|null|-?d+(?:.d*)?(?:[eE][+-]?d+)?/g, ']').替换(/(?:^|:|,)(?:s*[)+/g, ''))) {//json没问题}别的{//json不行}
编辑:新版本的 json2.js 进行了比上面更高级的解析,但仍然基于正则表达式替换(来自 @Mrchief 的评论 )
Something like:
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid JSON strings.
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(/"[^"\
]*"|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 )
这篇关于如何在不使用 Try/Catch 的情况下检查字符串是否为 JavaScript 中的有效 JSON 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!