【问题标题】:Adding values to JSON向 JSON 添加值
【发布时间】:2013-12-05 10:42:35
【问题描述】:

过去一个小时一直在努力解决这个问题,似乎无法弄清楚:

app.get('/bk/domains/get', function (req, res) {
   client.keys('*', function (e, d) {
       d.forEach(function (data) {
           client.hgetall(data, function (e, d) {
               res.json({'host': data, 'config': d});
           });
       });
   });
});

这是示例输出:

{
  "host": "test.com",
  "config": {
    "url": "http://test.com/test.html",
    "token": "source",
    "account": "test",
    "source": "google"
  }
}

现在,由于 res.json,它在从 client.hgetall 吐出第一个值后立即死亡。我想在这个 json 响应中添加大约 10 个其他值,但似乎无法使其正常工作。我该怎么做?

我试过这个:

app.get('/bk/domains/get', function (req, res) {
   var arr = [];
   client.keys('*', function (e, d) {
       d.forEach(function (data) {
           client.hgetall(data, function (e, d) {
               arr.push({'host': data, 'config': d});
           });
       });
   });
});

arr 始终为空。我还尝试将 arr 移到 app.get 之外,因为它可能是命名空间,但这也不起作用。

如何将 hgetall 中的 10 个值推送到单个数组中并将其作为 json 返回?

提前谢谢你!

【问题讨论】:

标签: javascript json node.js express


【解决方案1】:

由于客户端方法的异步特性,您可能会遇到问题。试试这个:

app.get('/bk/domains/get', function (req, res) {
   var arr = [], i = 0, numKeys;
   client.keys('*', function (e, d) {
        numKeys = d.length;
       d.forEach(function (data) {
           client.hgetall(data, function (e, d) {
               arr.push({'host': data, 'config': d});
               i++;
               console.log(arr);
               if(i == numKeys)
                res.json(arr);
           });
       });
   });
});

【讨论】:

  • 非常感谢!这完美地工作。我会记得将来这样做。再次感谢!
【解决方案2】:

这是来自 nodejs 网站:

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

基本上,正如一位用户所建议的那样,这是一个异步调用,您必须等待检索数据,然后让它在最后写入完整的数据,这样您就不会遇到任何中断。如需更多文档please review the docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多