user3447653
user3447653

Reputation: 4158

Reading json file in javascript

I have a json file in the following format:

{"Day": [{"NameofDay": "Beginning of year"}]}

If NameofDay has some text in it other than None, then I have to print that text. Else, I should not do anything.

I tried with the following code but I am not sure on how to add condition to it.

This is the first time I am using javascript. Any guidance would be really very helpful to me.

  function drawMessage(){
    var tt =  $.ajax({
       url: "findDay.json",
       dataType: "json",
       async: false
       });

    var jsonData = tt.responseJSON;
    var data = new google.visualization.DataTable(jsonData);
  }

Upvotes: 0

Views: 71

Answers (2)

squiroid
squiroid

Reputation: 14037

It should be done inside the $.ajax sucess callback method and it will be asynchronous.

$.ajax({
       url: "findDay.json",
       dataType: "json",
       success: function (data) {
        //Do stuff with the JSON data
        if(data.Day[0].NameofDay != 'None'){ //This condition be dependent on your requirement.
           var data = new google.visualization.DataTable(jsonData);
        }
        }
       });

Upvotes: 1

bozzmob
bozzmob

Reputation: 12584

Use a for loop to loop over the contents in the array and check if the property value is not equal to None as you mentioned.

Here is the code for the same-

  function drawMessage() {
      var tt = $.ajax({
          url: "findDay.json",
          dataType: "json",
          async: false,
          success: function(jsonData){
                      for (var i = 0; i < jsonData.Day.length; i++)
                         if (jsonData.Day[i].NameofDay != "None")
                             console.log(jsonData.Day[i].NameofDay)

      var data = new google.visualization.DataTable(jsonData);
  }

Upvotes: 1

Related Questions