简体   繁体   English

尝试/捕获以检查json不起作用

[英]try/catch to check a json doesn't work

I want to check if a string received is JSON and I tried the following code: 我想检查接收到的字符串是否为JSON,并尝试了以下代码:

try {
    JSON.parse(-10); // Same for "-10"
}catch(e) {
    console.log('inside catch');
}

The code never goes inside the catch block! 代码永远不会进入catch块! Why is it so? 为什么会这样呢?

A plain value is valid JSON . 普通值是有效的JSON That's why you're not getting 'inside catch' logged. 这就是为什么您未记录'inside catch'的原因。

 document.write(JSON.parse(-10)); 

This isn't valid JSON, however: 但是,这不是有效的JSON:

 try { JSON.parse('{'); }catch(e) { document.write('inside catch'); } 

As you can see, the try / catch is working just fine. 如您所见, try / catch正常运行。

I think -10 is valid to JSON.parse 我认为-10对JSON.parse有效

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

 try { var a = JSON.parse("{[]]]["); // Same for "-10" console.log(a); }catch(e) { console.log('inside catch'); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM