8

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']);
});
1
  • $.getJSON uses AJAX, which is asynchronous. The parsing happens in jQuery's internal callback function, which is outside the scope of the try block. Commented May 23, 2013 at 16:35

1 Answer 1

14

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

This still doesn't catch the error as there's apparently no timeout for the call.
This fails if the response is a valid json JSON. SyntaxError: Unexpected token o in JSON at position 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.