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.
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)
}
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"); 
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With