简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM