Talking about json Value of Object and Array

  • 2021-06-29 10:16:59
  • OfStack

Value by object:

The jQuery code is as follows


(function ($) {
      $.getJSON('ajax/test.json', function (data) {
        var items = [];

        $.each(data.comments, function (key, val) {
          items.push('<li class="' + 'tag' + val.class + '">' + '<a href="#">' + val.content + '</a>' + '</li>');
        });

        // No. 1 Labels 
        $('<ul/>', {
          'class':'',
          html:items.join('')
        }).appendTo('.tags');

        // No. 2 Labels 
        $('<ul/>', {
          'class':'alt',
          html:items.join('')
        }).appendTo('.tags');
      });
    })(jQuery);

The json code is as follows


{"comments":[
  {
    "class":"1",
    "content":"Lorem ipsum"
  },
  {
    "class":"2",
    "content":"Dolor sit amet"
  },
  {
    "class":"3",
    "content":"Consectetur adipiscing elit"
  },
  {
    "class":"2",
    "content":"Proin"
  },
  {
    "class":"4",
    "content":"Sagittis libero"
  },
  {
    "class":"1",
    "content":"Aliquet augue"
  },
  {
    "class":"1",
    "content":"Quisque dui lacus"
  },
  {
    "class":"5",
    "content":"Consequat"
  },
  {
    "class":"2",
    "content":"Dictum non"
  },
  {
    "class":"1",
    "content":"Venenatis et tortor"
  },
  {
    "class":"3",
    "content":"Suspendisse mauris"
  },
  {
    "class":"4",
    "content":"In accumsan"
  },
  {
    "class":"1",
    "content":"Egestas neque"
  },
  {
    "class":"5",
    "content":"Mauris eget felis"
  },
  {
    "class":"1",
    "content":"Suspendisse"
  },
  {
    "class":"2",
    "content":"condimentum eleifend nulla"
  }
]}

Value by array:

The jQuery code is as follows


(function ($) {
      $.getJSON('ajax/test_array.json', function (data) {
        var items = [];

        $.each(data.comments, function (key, val) {
          items.push('<li class="' + 'tag' + val[0] + '">' + '<a href="#">' + val[1] + '</a>' + '</li>');
        });

        // No. 1 Labels 
        $('<ul/>', {
          'class':'',
          html:items.join('')
        }).appendTo('.tags');

        // No. 2 Labels 
        $('<ul/>', {
          'class':'alt',
          html:items.join('')
        }).appendTo('.tags');
      });
    })(jQuery);

The json code is as follows


{"comments":[
  ["1", "Lorem ipsum"],
  ["2", "Dolor sit amet"],
  ["3", "Consectetur adipiscing elit"],
  ["2", "Proin"],
  ["4", "Sagittis libero"],
  ["1", "Aliquet augue"],
  ["1", "Quisque dui lacus"],
  ["5", "Consequat"],
  ["2", "Dictum non"],
  ["1", "Venenatis et tortor"],
  ["3", "Suspendisse mauris"],
  ["4", "In accumsan"],
  ["1", "Egestas neque"],
  ["5", "Mauris eget felis"],
  ["1", "Suspendisse"],
  ["2", "condimentum eleifend nulla"]
]}

The shared HTML code is as follows


 <div class="tags"></div>

It's clear that the amount of data in arrays is much smaller


Related articles: