0

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

1 Answer 1

2

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>";
}
Sign up to request clarification or add additional context in comments.

4 Comments

To expand upon this, if you use console.log(obj) you'll find out that it outputs attributes as the only content in the obj variable.
where can I find the output if I use console.log?
@BryanPosas See this documentation. Using the console really changes the like of a JS developer.
Thanks a lot sir for being helpful to a newbie.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.