I am trying to get data from an object deserialised from a JSON response. Please check my code below. The AJAX is working fine but don't know how to call data from keys. Please help.
我试图从一个JSON响应反序列化的对象中获取数据。请检查下面的代码。 AJAX工作正常,但不知道如何从密钥调用数据。请帮忙。
{
"data": {
"show_page": false,
"io": true,
"userslist": [{
"Captain Hook": {
"user_logo": "xyxImage.jpg",
"partner": "Jan 2013",
"usage": 123000,
"wise": 73000,
"server": 50000,
"status": "bronze",
"year": 2016,
"sum": 300000,
"order": 1
}
}]
}
}
$.ajax({
url: 'js/data.json',
type: 'GET',
dataType: 'json',
success : function(users, status){
console.log(users.data.userslist[0]); // Want to print "Captain Hook"
console.log(users.data.userslist[0].user_logo); // Want to print "logo"
console.log(users.data.userslist[0].partner); // Want to print "partner"
}
}
1 个解决方案
#1
1
Given your data structure the correct code would be users.data.userslist[index]
. To get the key of the object you would need to use Object.keys()
and you can then use that to retrieve the other required properties. Try this:
根据您的数据结构,正确的代码是users.data.userslist [index]。要获取对象的密钥,您需要使用Object.keys(),然后可以使用它来检索其他所需的属性。尝试这个:
success : function(users, status) {
var user = users.data.userslist[0];
var key = Object.keys(user)[0];
console.log(key); // = "Captain Hook"
console.log(user[key].user_logo); // = "xyxImage.jpg"
console.log(user[key].partner); // = "Jan 2013"
}
#1
1
Given your data structure the correct code would be users.data.userslist[index]
. To get the key of the object you would need to use Object.keys()
and you can then use that to retrieve the other required properties. Try this:
根据您的数据结构,正确的代码是users.data.userslist [index]。要获取对象的密钥,您需要使用Object.keys(),然后可以使用它来检索其他所需的属性。尝试这个:
success : function(users, status) {
var user = users.data.userslist[0];
var key = Object.keys(user)[0];
console.log(key); // = "Captain Hook"
console.log(user[key].user_logo); // = "xyxImage.jpg"
console.log(user[key].partner); // = "Jan 2013"
}