Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch JSON parsing errors in JQuery?

Tags:

jquery

getjson

In the following code, if the JSON I am trying to read in has a slight syntax error somewhere, then it simply doesn't say anything, I can't find any error shown in Chrome or Firefox which is telling me that it cannot parse the JSON field. Even this try/catch doesn't work.

How can I get my code to do something specific if the JSON cannot be parsed?

function init() {
    elemFront = $('div.flashcard div.bodyFront');
    elemBack = $('div.flashcard div.bodyBack');
    console.log('before');
    try {
        console.log('inside try');
        $.getJSON('data.txt', function(jsonResult) {
            console.log(jsonResult);
        });
    } 
    catch(err) {
        console.log('error');
    }
    console.log('after');
}

Addendum

Thanks @sagi, that worked, here's the code that catches syntax issues with JSON data:

$.get('data.txt', {}, function(data, response){
    var jsonResult;
    try {
        jsonResult = JSON.parse(data);
    }
    catch (e) {
        $('div.header').html('<span style="color:red">cannot load data because: "'+e+'"</span>');
    };
    $('div.bodyFront').html(jsonResult['one']);
});
like image 964
Edward Tanguay Avatar asked May 23 '13 16:05

Edward Tanguay


People also ask

How do I catch a JSON parse error?

The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

What is JSON parse in jquery?

parseJSON( json )Returns: String or Number or Object or Array or Booleanversion deprecated: 3.0. Description: Takes a well-formed JSON string and returns the resulting JavaScript value.

Does JSON parse throw an error?

JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

What is error parsing JSON?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.


1 Answers

if you are unsure of the response, you shouldn't use $.getJSON, instead you might want to do something like this

$.get('...', {}, function(data, response){
  var jsonResult;
  try {
    jsonResult = JSON.parse(data);
  }
  catch (e) {
    console.log("error: "+e);
  };
  // the rest of your code
});
like image 167
Sagish Avatar answered Oct 17 '22 08:10

Sagish