向JSON添加值
Adding values to JSON
在过去的一个小时里,我一直在努力解决这个问题,似乎无法解决:
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();
基本上,正如一位用户所建议的,这是一个异步调用,您必须等待检索数据,然后让它在最后写入完整的数据,这样您就不会有任何中断。有关进一步的文档,请查看文档。
相关文章:
- 在ListView中添加JSON数组中存储的图像-ReactNative
- 添加 json 文件注释
- 在AngularJS中删除和添加JSON中的项目
- 在表中添加JSON元素
- 添加Json数据作为dojogrid的源
- 在json本地存储中添加json对象时出错
- 如何在Javascript中添加JSON属性
- 分组并为多个键添加JSON对象
- 向可动态行添加JSON对象相关链接
- 添加JSON层到一个传单地图
- 如何添加""JSON中的字符
- 在运行时向JSON数组中添加JSON对象
- 在javascript中添加JSON对象到多维数组
- 如何使用javascript或jquery或angularjs为选定的键添加JSON值
- 向JSON对象中添加JSON对象
- 我在哪里添加JSON到谷歌地图Javascript
- 如何添加json没有复制(包括CasperJS代码)
- Javascript列表对象可以'不添加JSON?node . js,重火力点
- 在HTML数据属性上添加JSON是不是不好?
- 在JavaScript/jQuery中添加JSON数组