如何捕获JSON.parse()的异常? [英] How to catch exceptions of JSON.parse()?
问题描述
我必须解析的字符串来自FileReader()
,它可能是有效json文件的内容,或者可能是无效的(例如script.js)...
The string I have to parse comes from a FileReader()
, it may be the content of a valid json file or it may be invalid (eg a script.js) ...
问题是try/catch
似乎不适用于JSON.parse()
吗?
The problem is that try/catch
doesn't seem to work with JSON.parse()
?
下面的代码无法捕获到文件无效的异常JSON.parse: unexpected character at line 1 column 1 of the JSON data
.
The following code doesn't catch de exception JSON.parse: unexpected character at line 1 column 1 of the JSON data
with an invalid file.
try
{
var json = JSON.parse( content );
..
}
catch (e)
{
..
}
要进行第一次验证,我用( content.substr(0, 1) === '{' )
测试了第一个字符,但我认为这是不够的.
To make a first validation I test the 1st character with ( content.substr(0, 1) === '{' )
but I suppose it's insufficient.
实现此目标的最佳方法是什么?
What is the best way to achieve this ?
这个问题是错误地提出的.
This question was asked by mistake.
推荐答案
try-catch可以与JSON.parse
一起使用.在浏览器控制台中尝试以下操作,或使用SO的摘要功能:
try-catch does work with JSON.parse
. Try the following in your browser console or use SO's snippet feature:
try{
JSON.parse("b")
} catch(e) {
document.writeln("Caught: " + e.message)
}
这篇关于如何捕获JSON.parse()的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!