Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exceptions of JSON.parse()?

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) ...

The problem is that try/catch doesn't seem to work with JSON.parse() ?

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)
{
    ..
}

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 ?

EDIT: This question was asked by mistake.

like image 282
jeum Avatar asked May 28 '15 20:05

jeum


2 Answers

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)
}
like image 147
manojlds Avatar answered Sep 22 '22 00:09

manojlds


The try..catch block does work with JSON.parse, you're probably doing something else wrong. Try running this snippet to see it does indeed work:

var unexpectedJSON = '{a}';
try {
    JSON.parse(unexpectedJSON);
}
catch (e) {
    alert("Unexpected value in JSON"); 
}
like image 33
Marko Gresak Avatar answered Sep 20 '22 00:09

Marko Gresak