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.

+3


source to share


2 answers


try-catch works with JSON.parse

. Try the following in your browser console or use the SO snippet function:



try{ 
  JSON.parse("b") 
} catch(e) { 
  document.writeln("Caught: " + e.message)
}
      

Run codeHide result


+7


source


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"); 
}
      

Run codeHide result


+4


source







All Articles