向JSON添加值

Adding values to JSON

本文关键字:添加 JSON      更新时间:2024-03-09

在过去的一个小时里,我一直在努力解决这个问题,似乎无法解决:

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返回?

提前谢谢!

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

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);
           });
       });
   });
});

这来自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();

基本上,正如一位用户所建议的,这是一个异步调用,您必须等待检索数据,然后让它在最后写入完整的数据,这样您就不会有任何中断。有关进一步的文档,请查看文档。