0

I am using a .json file and jQuery's $.getJSON to fill divs with text, my code for that looks like this:

Code:

  $.getJSON("/js/content.json", function (data) {
  $(".lander .title").text(data.lTitle);
  $(".lander .subtitle").text(data.lSubtitle);
  $(".lander .text").html(data.lText).split('\n').join('<br/>');
});

JSON File:

{
    "comment": "Landing page",
    "lTitle": "Your webpage",
    "lSubtitle": "Your webpage subtitle",
    "lText": "Edit this text under >js/content.json< ",

    "lDetailsTitle": "Here goes the details title under the landing header.",
    "lDetailsText": "Here goes the details text."

}

What I am trying to do is use $parseJSON to check if the whole content.json is valid (Not just one string). The reason I want to do this is so that jquery can display an error message in the DOM so the user is aware why there is no text in the divs.

I've tried this, but it is not working:

var isValid = jQuery.parseJSON("/js/content.json");
if (isValid === true) {} else {
    $("#overlayMessage").css("display", "block");
    $("#overlayMessage .title").text("Oh no, we can't display this page!");
    $("#overlayMessage .text").text("An error occured with the file under: 'js/content.json'. Reason: Invalid.");
}

Is this possible to do at all, or can you only check if one string is valid?

Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91

3 Answers3

2

You probably want something like this:

try{
    var json = JSON.parse("invalid json");
}catch(err){
    console.log('json is invalid');
}

Output of running this in the browser is `json is invalid

DLeh
  • 23,806
  • 16
  • 84
  • 128
1

Provide a fail() callback to catch parse errors coming out of getJSON()

$.getJSON('/foo/bar.json')
  .done(function(d) {
    alert("success");
  })
  .fail(function(d) {
    alert("error");
  });

Related: Why does $.getJSON silently fail?

Community
  • 1
  • 1
jthomas
  • 858
  • 6
  • 19
0

jQuery.parseJSON() parses a JSON string, but you've provided a URI. You could use jQuery.get() to fetch the JSON as text, and then use jQuery.parseJSON() to check if it's valid.

$.get( "/js/content.json", function( data ) {
    try  {
        var jsonObj = jQuery.parseJSON( data );
    } catch(err) {
        $("#overlayMessage").css("display", "block");
        $("#overlayMessage .title").text("Oh no, we can't display this page!");
        $("#overlayMessage .text").text("An error occured with the file under: 'js/content.json'. Reason: Invalid.");
    }
});
Samuel
  • 16,923
  • 6
  • 62
  • 75