get label property of a json with getJSON and each

0

I'm wanting to get the label item of this json and I can not get the list out empty or undefined, I think it's a mulitidimentional array and it's missing one more level, I can not build the correct code it's what I need help with this thanks.

JSON:
{
  "entities": {
    "categories": [
      {
        "horror": {
          "id": 1,
          "label": "Terror"
        },
        "comedy": {
          "id": 2,
          "label": "Comedia"
        },
        "drama": {
          "id": 3,
          "label": "Drama"
        }
      }
    ]
}

// SCRIPT

$(document).ready( function() {
 $.getJSON("/books-schema.json",
        function(data){
          $.each(data.entities.categories, function(i,item){
            $("<li>").html(item.label).appendTo("#categoria");
          });
        });
 });
    
asked by Sixto Mujica 15.03.2017 в 00:24
source

2 answers

2

Inside the object entities there is a property called categories of type array ( [] ); This array contains only one element (object) with three properties: "horror", "comedy" and "drama". For your code to work (using a JSON object as illustrated), you have to change the callback function within the .getJSON statement as follows:

function(data) {
  $.each(data.entities.categories[0], function(i, item) {
    $("<li>").html(item.label).appendTo("#categoria");
  });
});

In this way the $.each instruction will scroll each element within the first and only element (0) of the categories array, returning the internal list as you search.

NOTE: If you have access to the code of the application or service generated by said JSON, you could change its structure so that it is generated in the following way and your code works as you do:

{
  "entities": {
    "categories": {
      "horror": {
        "id": 1,
        "label": "Terror"
      },
      "comedy": {
        "id": 2,
        "label": "Comedia"
      },
      "drama": {
        "id": 3,
        "label": "Drama"
      }
    }
  }
}

With this scheme categories becomes an object with the individual properties "horror", "comedy" and "drama" and can be accessed directly using data.entities.categories . Here you can see the example of this.

    
answered by 15.03.2017 / 00:49
source
0

I continue with that theme now I want to get the id of that array in the generated li I am using this structure I get the id but the last one the id 3 is repeated in all, give me a hand as I can get the respective id for each label. Thank you very much.

SOLUTION:

$.each(data.entities.categories[0], function(i, item) {
  $('#categoria').append($('<li>').attr('id', item.id).html(item.label));

});

<ul id="categoria">
<li id="1">Terror</li>
<li id="2">Comedia</li>
<li id="3">Drama</li>
 </ul>
    
answered by 15.03.2017 в 18:30