1

How would one assign the body of request.get('http://someurl/file.json', function(err, response, body) {}) to a variable?

For example:

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

Thanks in advance :)

stackunderflow
  • 1,644
  • 6
  • 24
  • 40

2 Answers2

1
var myvariable1;

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

the body is not available until the callback is complete. I don't think there is any shorthand for callbacks that allows what you want. However, there is a shorthand for promises. You could use the bluebird npm module to try and promisify this. You could then do ... myvar = request.get('path'); .... myvar would then contain the result of the resolved promise ON resultion (not before) - this works in an AngularJS environment for sure and prob would work in pure Node too - Hope that gives some food for thought.

You could also use something like the q library to promisify this (which I believe is now in Node by default).

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.

Worse case scenario if this doesn't work then you resort COULD resort to ...

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

Which puts you back kinda where you started lol :)

PS I have ignored error handling with promise CATCH blocks for the sake of simplicity

danday74
  • 52,471
  • 49
  • 232
  • 283
  • thanks, I was hoping to avoid the callback and make it cleaner by simply taking the response body and storing into a variable. Oh and you should have `myvariable1=body.Name1.prop` no? – stackunderflow Jan 15 '16 at 11:09
  • yes myvariable1=body.Name1.prop ... the body is not available until the callback is complete. I don't think there is any shorthand for callbacks that allows what you want. However, there is a shorthand for promises. You could use the bluebird npm module to try and promisify this. You could then do ... myvar = request.get('path'); .... myvar would then contain the result of the resolved promise ON resultion (not before) - this works in an AngularJS environment for sure and prob would work in pure Node too - Hope that gives some food for thought. – danday74 Jan 15 '16 at 11:18
  • This is an interesting idea though I would really love to shorthand this. If all you want is the response, it's easy to test for it once you have it assigned to a variable. I hope this gets some more attention. Thanks though :) – stackunderflow Jan 15 '16 at 11:35
  • bluebird and promisifying request.get('http://someurl/file.json') is the solution you want for minimalistic code :) – danday74 Jan 15 '16 at 11:38
  • I thought as much, I just find it hard to understand Promises. Still some further reading wouldn't hurt. Thanks for you help. – stackunderflow Jan 15 '16 at 12:04
  • i did as well, im really thick, but promises are simple :) basically lets assume you can promisify request.get(http://localhost/file.json) using bluebird ... promisify means to a method that uses a callback to use promises instead. OK so if you can promisify it then request.get now returns a promise instead. Promises have a THEN method which is called when the promise is rejected or resolved. The THEN method has 2 params, the first params is the function to call on resolution (success) then second method is the function to call on reject (failure). However, some libraries (such as angular) .. – danday74 Jan 15 '16 at 12:14
  • shortcut this even further by allowing var mypromise = methodReturningAPromise; mypromise is now a promise and has a then method. However, on promise resolution the shorthand I am talking about bypasses this and automatically assigns the resolution value of the promise to the mypromise variable on promise resolution such that there is no need to call then. Remember this is only a shorthand, it is not the usual use case. Usually you call THEN instead. Hope this demystifies promises a little for you :) – danday74 Jan 15 '16 at 12:17
0

There's no JSON-object in javascript. What you can do is to parse the data into an array, like this

var json = request.get(http://localhost/file.json);
var parsed = JSON.parse(json);
var arr = [];

for(var i in parsed){
    arr.push(parsed[i]);
}
Tompina
  • 726
  • 1
  • 9
  • 25