patrickhuang94
patrickhuang94

Reputation: 2115

Access data in JSON format

I'm doing a GET http request for Google Civic's API, where I'm providing an address and receiving members of the U.S. government based on where the provided address is located.

//var options has the host, path, etc.
var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log(chunk.normalizedInput) //returns 'undefined'
  });
});

chunk is printing this out:

enter image description here

And to my understanding, to access data in normalizedInput, I'd do chunk.normalizedInput, right? Why is it returning undefined?

Upvotes: 0

Views: 64

Answers (1)

Daphoque
Daphoque

Reputation: 4678

You retrieve string by stream, you need to wait the end of the stream and parse the string before manipulate object

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  var chunks = [];
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
   chunks.put(chunk);
  });
  res.on('end', function () {
   console.log(JSON.parse(chunks.join("")).normalizedInput);
  });
});

Upvotes: 1

Related Questions