Search code examples
javascriptarraysjsonnode.jsyahoo-api

How do I extract data from a Yahoo Finance JSON using node.js?


I built out a simple request function to get a JSON from the Yahoo Finance API but am having trouble extracting data from the JSON.

Here's my function

var request = require("request");

var stock_url = "http://finance.yahoo.com/webservice/v1/symbols/FB/quote?format=json&view=%E2%80%8C%E2%80%8Bdetail";

request(stock_url, function (error, response, body) { 
    if (!error && response.statusCode == 200) {  
        var stock_data = body;
        console.log("Yahoo Finance API: ", stock_data)
        var stock_price = stock_data.list.resources[0].resource.fields.price;
        console.log("stock_price: ", stock_price);       
    };
});

The JSON returned is stored in var stock_data successfully and I then try to extract the "price" data with var stock_price = stock_data.list.resources[0].resource.fields.price but am getting a TypeError: cannot read property 'resources' of undefined.

Below is the JSON, I've tried multiple derivatives for var stock_price with no luck. Any help is much appreciated.

{
  "list": {
    "meta": {
      "type": "resource-list",
      "start": 0,
      "count": 1
    },
    "resources": [
      {
        "resource": {
          "classname": "Quote",
          "fields": {
            "name" : "Facebook, Inc.",
            "price" : "116.620003",
            "symbol" : "FB",
            "ts" : "1465588800",
            "type" : "equity",
            "utctime" : "2016-06-10T20:00:00+0000",
            "volume" : "18510826"              
          }
        }
      }
    ]
  }
}

Solution

  • Request returns body as string value.

    You should then parse it with var stock_data = JSON.parse(body).

    BTW you can use existing yahoo-finance implementations for node and avoid to rewrite it you own.