【问题标题】:Extracting data from JSON object containing arrays从包含数组的 JSON 对象中提取数据
【发布时间】:2017-09-16 00:19:59
【问题描述】:

我正在尝试从服务器的响应正文中提取数据。我已经浏览了一段时间的互联网,发现了一些“应该”工作但没有工作的东西。该请求是一个返回 JSON 对象的 https 请求。

//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 对象。

【问题讨论】:

    标签: json node.js api npm https


    【解决方案1】:

    也许你应该console.log(body.data.listing[i].listingType)

    修复错误的另一个好方法是:

    body.data.listings.forEach(function(element,index){
       //do something
    }
    

    【讨论】:

      【解决方案2】:

      问题出在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++){
      

      它应该正确地遍历数组中的所有项目。 其次,正如 James 所说,您应该在循环中使用 body.data.listings[i].listingType 而不是 data.listings[i].listingType

      【讨论】:

      • 我仍然收到 TypeError: Cannot read property 'listings' of undefined
      • @ChristopherLittlewood 这意味着body 对象没有data 属性。尝试通过打印console.log(JSON.stringify(body)) 进行调试
      猜你喜欢
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 2019-09-20
      • 2022-10-22
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多