D. Matthew
D. Matthew

Reputation: 45

How to read JSON file from URL and assign it into a global variable in NodeJS?

var url = 'https://myurl.com/file.json';
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
     var jsonObject = JSON.parse(body);
     console.log(jsonObject);
  }
});

I've found the way to get JSON file from URL but it's a little bit struggle for me to assign it to a global variable. In this case, how can I deal with the jsonObject?

Upvotes: 0

Views: 3877

Answers (2)

Pixelmixer
Pixelmixer

Reputation: 319

Technically to make it a global variable you just need to define it outside of your callback function.

var url = 'https://myurl.com/file.json';
var jsonObject;
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
     jsonObject = JSON.parse(body);
     console.log(jsonObject);
  }
});

However, based on what I can see here I don't think that will solve whatever problem you're trying to solve. The reason is that request's callback is handled asynchronously. So even if you assign that to a global variable it won't be accessible in your other code later down the line.

var url = 'https://myurl.com/file.json';
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
     var jsonObject = JSON.parse(body);

     // Rest of your application that needs access to jsonObject can do here...
     // You can also pass it on to another function by running something like `processResponse( jsonObject )`;
  }
});

Upvotes: 1

Inder R Singh
Inder R Singh

Reputation: 652

This is how you should do it.

var jsonObject;
var url = 'https://myurl.com/file.json';
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
     jsonObject = JSON.parse(body);
     console.log(jsonObject);
  }
});

Upvotes: 0

Related Questions