javascript - 试图遍历一个节点得到休息返回

标签 javascript json

我正在尝试遍历通过 get 请求返回的数据。我试图像使用 JSON 格式一样遍历它,但我对此很陌生,不确定它是否返回它以 JSON 格式识别的内容,或者它是否将其识别为字符串,这就是为什么我无法让它识别诸如 info.data.items 之类的东西。这是我使用节点的获取请求,基本身份验证。

这是从我的 get 请求返回的示例数据以及我实际尝试迭代的内容。

{"data":{"items":[{"date":"2017-02-02","revenue":111,"impressions":000},{"date":"2017-02-03","revenue":123,"impressions":0000,},"message":"Top 2 rows returned."}

function rData(key, secret, account_id) {

  var https = require('https');

  var options = {

    host: 'api.urlhere.com',
    port: 443,
    path: 'path',

    // authentication headers

    headers: {

      'Authorization': 'Basic ' + new Buffer(key + ':' + secret).toString('base64')

    }
  };
  var request = https.get(options, function(res) {

    var body = "";

    res.on('data', function(data) {

      body += data;

    });

    res.on('end', function() {

      //console.log(body);
      callNextFunction(body);
    })

    res.on('error', function(e) {

      console.log("Got error: " + e.message);

    });
  });
}

然后这是我尝试迭代数据的下一个函数。通过这个函数后,我得到了错误,

TypeError: Cannot read property 'items' of undefined

function callNextFunction(rBody) {

  var rData = rBody;

  console.log("Data transfer sucessful: " + rData); // Works up to this point.

  rData.data.items.forEach(function(info) {

    var rev = info.revenue;
    console.log("Revenue: " + rev);
  })
}

最佳答案

查看您的 JSON 我可以看到以下问题

{"data":{"items":[{"date":"2017-02-02","revenue":111,"impressions":000},{"date":"2017-02-03","revenue":123,"impressions":0000,},"message":"Top 2 rows returned."} <-- this should probably be a ']' not sure

根据您的问题,我认为您想要访问数据的属性。 尝试以下操作

function callNextFunction(rBody) {

  var rData = JSON.parse(rBody);

  console.log("Data transfer sucessful: " + rData); // Works up to this point.
  $.each(rData.data.items, function(i, info) {
    if (info.date) {
       //this info will contain the item with "date" "revenue"...
       var rev = info.revenue;
       console.log("Revenue: " + rev);
    }
    else if (info.message) {
        // this is the information that contains the "message":"Top 2 rows returned."
    }
  });
}

关于javascript - 试图遍历一个节点得到休息返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42585234/

相关文章:

javascript - 使用 JavaScript 获取元素的样式

android - 奇怪的 SOAP 响应,是 JSON 吗?如何解析它?

java - 关于 Callable 接口(interface)中的 call() 方法。在call()中调用其他静态方法时,是否会阻塞并影响性能?

ruby-on-rails - 如何在 Ruby on Rails 中使用 PostgreSQL JSON 数组查询 ActiveRecord::Relation

jquery - 使用 jquery FullCalendar 的多个事件源

javascript - 使用 AngularStrap 的响应式导航栏折叠动画

javascript - 为什么 Array.prototype.includes.bind 行为异常?

javascript - jQuery:如果列表项已选中内部单选按钮,则添加类

javascript - 如何使用 map 方法将查询参数传递给 api,并将每个 json 响应连接到 react 中的 setState?

.net - jqGrid - 如何配置 jsonreader(与 Jayrock 一起使用)?