繁体   English   中英

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

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

我想检查接收到的字符串是否为JSON,并尝试了以下代码:

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

代码永远不会进入catch块! 为什么会这样呢?

普通值是有效的JSON 这就是为什么您未记录'inside catch'的原因。

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

但是,这不是有效的JSON:

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

如您所见, try / catch正常运行。

我认为-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