将requestjs响应分配给variables

如何将一个request.get('http://someurl/file.json', function(err, response, body) {})request.get('http://someurl/file.json', function(err, response, body) {})赋值给一个variables?

例如:

file.json

 { "Name1": { "prop": "value" }, "Name2": { "prop": "value" } } 

app.js

 var json = request.get(http://localhost/file.json); json = JSON.parse(json); console.log(json["Name1"].prop); 

提前致谢 :)

 var myvariable1; request.get('http://someurl/file.json', function(err, response, body) { myvariable1=response.Name1.prop; }) 

在callback完成之前,主体不可用。 我不认为有callback允许你想要的简写。 但是,有一个承诺的简写。 你可以使用蓝鸟NPM模块尝试和promisify这一点。 你可以做… myvar = request.get('path'); …. myvar然后将包含parsing承诺的结果ON resultion(而不是之前) – 这在AngularJS环境中工作肯定和概率将工作在纯节点也希望提供一些思考的食物。

你也可以使用类似于q库的东西promisify这(我相信现在在默认情况下在节点)。

 function getMyData() { var def=q.defer(); request.get('http://someurl/file.json', function(err, response, body) { def.resolve(response.Name1.prop); }) return def.promise(); } // myvar will have the result of the resolution on resolution (not before) var myvar = getMyData(); // to test this approach you might want to use a settimeout to repeatedly dump the value of myvar every X ms. // Again this approach deffo works in Angular and hopefully works in Node too. 

更糟糕的情况下,如果这不起作用,那么你度假村可以诉诸…

 var myvar; getMyData().then(function(data) { myvar = data; )); 

哪个让你回到你开始笑的地方:)

PS为了简单起见,我忽略了承诺CATCH块的error handling

在JavaScript中没有JSON对象。 你可以做的是将数据parsing成一个数组,像这样

 var json = request.get(http://localhost/file.json); var parsed = JSON.parse(json); var arr = []; for(var i in parsed){ arr.push(parsed[i]); } 

request.get()返回一个requestjs对象,而不是提取的数据。

您需要提供使用数据的callback函数。

就像这里的requestjs文档中所解释的那样

你可以这样做:

 var request = require('request'); var JSON = require('JSON'); function handler(error, response, body) { var json = JSON.parse(body); console.log(json); } request.get("http://headers.jsontest.com/",handler);