Sebastian Olsen
Sebastian Olsen

Reputation: 10878

jQuery - Check if a .json file is valid

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?

Upvotes: 0

Views: 1238

Answers (3)

Samuel
Samuel

Reputation: 17171

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

Upvotes: 0

jthomas
jthomas

Reputation: 858

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?

Upvotes: 1

DLeh
DLeh

Reputation: 24395

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

Upvotes: 2

Related Questions