Bryan P
Bryan P

Reputation: 4202

How to get json data properly in javascript

I'm trying to get the data inside of "attributes" in these json format, but I always get undefined

{ "data": [ 
   { "attributes":     
      {
         "id":"4977",
         "book_id":"651284829",
         "provider_id":"1",
         "title":"\u96e8\u8272\u30b3\u30b3\u30a2",
         "author":"IAM, K.K.",
         "price":"170.00",
         "rating":"4"
      },
      ...
   }
}

This is my code which always returns undefined:

for ( var obj in json.data) {
    var att = obj.attributes;
    html += "<p>" + att.author + "</p>";
}

Upvotes: 0

Views: 69

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

You're iterating over the keys of the properties of json.data, not the values of those properties.

Change

var att = obj.attributes;

to

var att = json.data[obj].attributes;

To make it clearer, a different name could be used :

for (var key in json.data) {
    var obj = json.data[key];
    var att = obj.attributes;
    html += "<p>" + att.author + "</p>";
}

Upvotes: 2

Related Questions