javascript 如何验证 JSON 字符串 JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7574208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:35:39  来源:igfitidea点击:

How to validate a JSON String JQuery

javascriptjqueryjsonvalidation

提问by kamaci

I tried that:

我试过了:

var c = $.parseJSON(something here)

and I control that:

我控制:

c === undefined

This works however it throws error while trying to parse an invalid JSON string. I don't want it throw that error.

这有效,但是在尝试解析无效的 JSON 字符串时会引发错误。我不希望它抛出那个错误。

Any advices?

有什么建议吗?

回答by Clive

It's generally considered bad practice to suppress/ignore errors, instead why not use a try-catch blockto capture the exception and do something with it:

抑制/忽略错误通常被认为是不好的做法,为什么不使用try-catch 块来捕获异常并对其进行处理:

try {
  var c = $.parseJSON(something here);
}
catch (err) {
  // Do something about the exception here
}

If you really don't need to do anything about the exception at least put a comment to that effect in your try-catchblock, it'll make your code more readable when you come back to it later.

如果你真的不需要对异常做任何事情,至少在你的try-catch块中添加一个注释,它会让你的代码在你稍后回来时更具可读性。