Kelly Norton Kelly Norton - 6 months ago 21
JSON Question

Parsing nested JSON with NODE

Second question for the day :)

Still working on my first ever app, and I've hit a bit of a snag using an API that returns currency exchange values. I need to extract the current AUD value from this JSON :

{"base":"USD","date":"2016-05-30","rates":{"AUD":1.3919,"BGN":1.7558,"BRL":3.6043,"CAD":1.3039,"CHF":0.99273,"CNY":6.5817,"CZK":24.258,"DKK":6.6765,"GBP":0.68341,"HKD":7.7688,"HRK":6.7195,"HUF":281.72,"IDR":13645.0,"ILS":3.8466,"INR":67.139,"JPY":111.19,"KRW":1190.9,"MXN":18.473,"MYR":4.1175,"NOK":8.3513,"NZD":1.4924,"PHP":46.73,"PLN":3.9447,"RON":4.0428,"RUB":65.89,"SEK":8.3338,"SGD":1.3811,"THB":35.73,"TRY":2.9565,"ZAR":15.771,"EUR":0.89775}}


Here is the code I am using:

var http = require('http');
var options = {
host: 'api.fixer.io',
port: 80,
path: '/latest?base=USD',
method: 'GET'
};

http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
const json = JSON.parse(chunk);
rate = json.AUD;
console.log(rate);
});
}).end();


Unfortunately this doesn't work, and I assume that is because the JSON is nested? How do I go about querying this nested string correctly?

I also know I need to tighten up my handling of chunks, but it's baby steps for me right now :)

Thank you!

Answer

You should wait for whole data first, or use one of the streaming parsers instead (for example: https://github.com/dominictarr/JSONStream).

That is because "chunk" is not all data at once - it may be just part of it, which means it's not a valid JSON itself.

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  var data = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    data += chunk;
  });
  res.on('end', function () {
    const json = JSON.parse(data);
    // As @huaoguo mentioned, it should be `json.rates.AUD`, not `json.AUD`
    rate = json.rates.AUD;
    console.log(rate);
  });
}).end();

Also, as @huaoguo mentioned, there should be json.rates.AUD instead of json.AUD.

Comments