How do I catch JSON.parse () exceptions?
The line I have to parse comes from FileReader()
, it might be the content of a valid json file, or it might be invalid (like script.js) ...
The problem is what try/catch
doesn't seem to work with JSON.parse()
?
The following code does not throw JSON.parse: unexpected character at line 1 column 1 of the JSON data
an invalid file exception .
try
{
var json = JSON.parse( content );
..
}
catch (e)
{
..
}
To do the first check, I am testing the 1st character with ( content.substr(0, 1) === '{' )
, but I guess it is not enough.
What is the best way to achieve this?
EDIT: This question was asked by mistake.
source to share
The block is try..catch
working with JSON.parse
, you are probably doing something else wrong. Try running this snippet to see how it actually works:
var unexpectedJSON = '{a}';
try {
JSON.parse(unexpectedJSON);
}
catch (e) {
alert("Unexpected value in JSON");
}
source to share