从包含数组的JSON对象提取数据
问题描述:
我试图从服务器的响应正文中提取数据。我浏览了一段时间的互联网,发现了一些“应该”起作用的东西,但没有。该请求是一个返回JSON对象的https请求。从包含数组的JSON对象提取数据
//Open the request:
request({
//Set the request Method:
method: 'POST',
//Set the headers:
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer "+ token,
'X-Originating-Ip': ipAddress
},
//Set the URL:
url: 'URL',
//Set the request body:
body: { 'Body here'},
}, function(error, response, body){
//Alert the response body:
for(var i=0; body.data.listings.length; i++){
console.log(data.listings[i].listingType);
}
console.log(response.statusCode);
});
出于安全原因,我不能显示实际的响应体,但它是一个包含多个阵列JSON对象。
答
或许你应该console.log(body.data.listing[i].listingType)
另一种很好的做法,修复错误是:
body.data.listings.forEach(function(element,index){
//do something
}
答
的问题是在for循环
for(var i=0; body.data.listings.length; i++){
console.log(data.listings[i].listingType);
}
首先的终止条件循环是body.data.listings.length
,它将始终返回listings
的长度,并且对于非空数组始终是真的。您需要将循环声明更改为
for(var i=0; i<body.data.listings.length; i++){
它应正确遍历数组中的所有项目。其次,正如詹姆斯所说,你应该在循环内使用body.data.listings[i].listingType
而不是data.listings[i].listingType
。
我仍然得到一个TypeError:无法读取未定义的属性'列表' –
@ChristopherLittlewood这意味着'body'对象没有'data'属性。尝试使用'console.log(JSON.stringify(body))'进行打印调试 – shawon191