1

I get an JSON array via an Ajax request. This one looks like this:

{  
   "data":{  
      "title":"Frau",
      "academic_title":null,
      "first_name":"Lynda",
      "last_name":"McCrow",
      "company":"Tekfly",
      "street":"Sage",
      "zip":"4860-077",
      "country":"Portugal",
      "city":"Quinta",
      "phone":"6727086107",
      "fax":"4941912651",
      "mobile":"3722716317",
      "email":"lmccrow7@newyorker.com",
      "web":"shop-pro.jp",
      "mailbox":"81-0982335",
      "mailbox_country":"Indonesia",
      "mailbox_zip":null,
      "mailbox_city":"Susoh",
      "birthday":"1977-02-11"
   }
}

But I have no idea, how to access the JSON array. I already tried all of this:

success: function(data) {
 console.log(data[0].data.title);
 console.log(data[0].title);
 console.log(data.data[0].title);
 console.log(data.title);
}

Can you guys give me a hint?

Kind regards

Jan
  • 1,180
  • 3
  • 23
  • 60

2 Answers2

6

You have tried everything except:

data.data.title

It's an Object and you need to use Object.key() or something to iterate. Technically, it's like this:

// Inside your function, this is what gets passed.
data = {  
   "data":{  
      "title":"Frau",
      "academic_title":null,
      "first_name":"Lynda",
      "last_name":"McCrow",
      "company":"Tekfly",
      "street":"Sage",
      "zip":"4860-077",
      "country":"Portugal",
      "city":"Quinta",
      "phone":"6727086107",
      "fax":"4941912651",
      "mobile":"3722716317",
      "email":"lmccrow7@newyorker.com",
      "web":"shop-pro.jp",
      "mailbox":"81-0982335",
      "mailbox_country":"Indonesia",
      "mailbox_zip":null,
      "mailbox_city":"Susoh",
      "birthday":"1977-02-11"
   }
};

for (var key in data.data) {
  console.log(`${key}: ${data.data[key]}`);
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
3

data is not an array, nor JSON, it's an object literal. Your last try comes close, but you need to access

data.data.title

or you could destructure data in the success param

success: function({data}) {
    // now you could access data.title directly
    console.log(data.title);
}
baao
  • 71,625
  • 17
  • 143
  • 203