使用javascript从json对象获取值
我试图从请求返回的json对象中获取特定值。但是我使用的sintax不起作用。返回的值是未定义的。如何在json对象中获取key使用javascript从json对象获取值,javascript,json,Javascript,Json,我试图从请求返回的json对象中获取特定值。但是我使用的sintax不起作用。返回的值是未定义的。如何在json对象中获取keyname的值 响应存储在客户变量中 $http.get('url'). then(function successCallback(response){ var costumers = response; console.log(costumers['data']['costumers']['name']); }, func
name
的值
响应存储在客户变量中
$http.get('url').
then(function successCallback(response){
var costumers = response;
console.log(costumers['data']['costumers']['name']);
}, function errorCallback(response){
});
Json对象
{data: "{"costumers":[{"id":"1","name":"John"},{"id":"2","name":"Mary"}]}"}
在您的例子中,
customers
是一个对象数组,因此您必须指定要从中获取值的对象的索引,例如:
costumers['data']['costumers'][0]['name']
______________________________^^^
0
索引将返回第一个对象:
{"id":"1","name":"John"}
您可以始终循环查看客户的所有对象,并且可以检查返回的对象是否具有所需的“属性”,如:
if( costumers['data']['costumers'][0].hasOwnProperty('name') ){
console.log( costumers['data']['costumers'][0]['name'] );
}
customers
是一个数组,要访问数组元素,需要将索引写入它后面的方括号中。在这种情况下,如果要访问数组的第一个元素(索引0),可以这样做:
$http.get('url').
then(function successCallback(response){
var costumers = response;
console.log(costumers['data']['costumers'][0]['name']);
}, function errorCallback(response){
});
或使用for循环记录所有客户:
$http.get('url').
then(function successCallback(response){
var costumers = response;
for(let customer of costumers['data']['costumers']) {
console.log(customer['name']);
}
}, function errorCallback(response){
});
所有这些只有在对象语法正确的情况下才起作用,它应该如下所示:
{data: {costumers:[{id:"1",name:"John"},{id:"2",name:"Mary"}]}}
而不是您发布的对象。customers['data']['customers'][0]['name']
上述注释是正确的,或者您可以省去所有不必要的引号,只使用customers.data.customers[0].name
。(我不想对“json对象”发表评论),所以您的数据示例在语法上是无效的。。。你能举个真实的例子吗?它是字符串形式的还是您已经解析了它?