Thursday, March 27, 2014

Javascript Tutorial - Using JSON Services

One of the commonly performed tasks in Javascript is accessing JSON services. However, due to the nature of JSON, it is often not easy to parse the JSON result.

In this tutorial, you will learn how to access a JSON service that returns the prices of stocks. The Yahoo API is one such service. To use it, call it with the following query string:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json

In the above string, the stock symbols are bolded – YHOO (Yahoo) and AAPL (Apple). The %22 surrounding the stock symbols is the URL encoded equivalent of the double quote (“) and the %2C is the equivalent of the comma (,). Hence, the above snippet of:

(%22YHOO%22%2C%22AAPL%22)

is the same as:

("YHOO","AAPL")

If you want the price of additional stocks, simply add more symbols separated with commas, like this:

("YHOO","AAPL","MSFT","FB")

The Yahoo API service returns the result of the query as a JSON string. Here is one sample result:

{"query":{"count":2,"created":"2014-03-27T11:24:23Z","lang":"en-us","results":{"quote":[{"symbol":"YHOO","Ask":"35.65","AverageDailyVolume":"17916300","Bid":"35.46","AskRealtime":"35.65","BidRealtime":"35.46","BookValue":"12.89","Change_PercentChange":"-0.48 - -1.34%","Change":"-0.48","Commission":null,"ChangeRealtime":"-0.48","AfterHoursChangeRealtime":"N/A - N/A","DividendShare":"0.00","LastTradeDate":"3/26/2014","TradeDate":null,"EarningsShare":"1.26","ErrorIndicationreturnedforsymbolchangedinvalid":null,"EPSEstimateCurrentYear":"1.58","EPSEstimateNextYear":"1.80","EPSEstimateNextQuarter":"0.37","DaysLow":"35.45","DaysHigh":"36.74","YearLow":"22.70","YearHigh":"41.72","HoldingsGainPercent":"- - -","AnnualizedGain":null,"HoldingsGain":null,"HoldingsGainPercentRealtime":"N/A - N/A","HoldingsGainRealtime":null,"MoreInfo":"cn","OrderBookRealtime":null,"MarketCapitalization":"35.783B","MarketCapRealtime":null,"EBITDA":"1.031B","ChangeFromYearLow":"+12.75","PercentChangeFromYearLow":"+56.17%","LastTradeRealtimeWithTime":"N/A - 35.45","ChangePercentRealtime":"N/A - -1.34%","ChangeFromYearHigh":"-6.27","PercebtChangeFromYearHigh":"-15.03%","LastTradeWithTime":"Mar 26 - 35.45","LastTradePriceOnly":"35.45","HighLimit":null,"LowLimit":null,"DaysRange":"35.45 - 36.74","DaysRangeRealtime":"N/A - N/A","FiftydayMovingAverage":"37.8056","TwoHundreddayMovingAverage":"36.2834","ChangeFromTwoHundreddayMovingAverage":"-0.8334","PercentChangeFromTwoHundreddayMovingAverage":"-2.30%","ChangeFromFiftydayMovingAverage":"-2.3556","PercentChangeFromFiftydayMovingAverage":"-6.23%","Name":"Yahoo Inc.","Notes":null,"Open":"36.36","PreviousClose":"35.93","PricePaid":null,"ChangeinPercent":"-1.34%","PriceSales":"7.75","PriceBook":"2.79","ExDividendDate":null,"PERatio":"28.52","DividendPayDate":null,"PERatioRealtime":null,"PEGRatio":"3.14","PriceEPSEstimateCurrentYear":"22.74","PriceEPSEstimateNextYear":"19.96","Symbol":"YHOO","SharesOwned":null,"ShortRatio":"1.20","LastTradeTime":"4:00pm","TickerTrend":" ====== ","OneyrTargetPrice":"40.71","Volume":"20940480","HoldingsValue":null,"HoldingsValueRealtime":null,"YearRange":"22.70 - 41.72","DaysValueChange":"- - -1.34%","DaysValueChangeRealtime":"N/A - N/A","StockExchange":"NasdaqNM","DividendYield":null,"PercentChange":"-1.34%"},{"symbol":"AAPL","Ask":"540.62","AverageDailyVolume":"11499500","Bid":"540.24","AskRealtime":"540.62","BidRealtime":"540.24","BookValue":"145.313","Change_PercentChange":"-5.21 - -0.96%","Change":"-5.21","Commission":null,"ChangeRealtime":"-5.21","AfterHoursChangeRealtime":"N/A - N/A","DividendShare":"12.20","LastTradeDate":"3/26/2014","TradeDate":null,"EarningsShare":"40.233","ErrorIndicationreturnedforsymbolchangedinvalid":null,"EPSEstimateCurrentYear":"42.82","EPSEstimateNextYear":"46.47","EPSEstimateNextQuarter":"8.60","DaysLow":"538.86","DaysHigh":"549.00","YearLow":"385.10","YearHigh":"575.14","HoldingsGainPercent":"- - -","AnnualizedGain":null,"HoldingsGain":null,"HoldingsGainPercentRealtime":"N/A - N/A","HoldingsGainRealtime":null,"MoreInfo":"cnsprmiIed","OrderBookRealtime":null,"MarketCapitalization":"481.5B","MarketCapRealtime":null,"EBITDA":"56.565B","ChangeFromYearLow":"+154.68","PercentChangeFromYearLow":"+40.17%","LastTradeRealtimeWithTime":"N/A - 539.78","ChangePercentRealtime":"N/A - -0.96%","ChangeFromYearHigh":"-35.36","PercebtChangeFromYearHigh":"-6.15%","LastTradeWithTime":"Mar 26 - 539.78","LastTradePriceOnly":"539.78","HighLimit":null,"LowLimit":null,"DaysRange":"538.86 - 549.00","DaysRangeRealtime":"N/A - N/A","FiftydayMovingAverage":"530.276","TwoHundreddayMovingAverage":"524.312","ChangeFromTwoHundreddayMovingAverage":"+15.468","PercentChangeFromTwoHundreddayMovingAverage":"+2.95%","ChangeFromFiftydayMovingAverage":"+9.504","PercentChangeFromFiftydayMovingAverage":"+1.79%","Name":"Apple Inc.","Notes":null,"Open":"547.11","PreviousClose":"544.99","PricePaid":null,"ChangeinPercent":"-0.96%","PriceSales":"2.79","PriceBook":"3.75","ExDividendDate":"Feb  6","PERatio":"13.55","DividendPayDate":"Feb 13","PERatioRealtime":null,"PEGRatio":"0.60","PriceEPSEstimateCurrentYear":"12.73","PriceEPSEstimateNextYear":"11.73","Symbol":"AAPL","SharesOwned":null,"ShortRatio":"1.70","LastTradeTime":"4:00pm","TickerTrend":" ====== ","OneyrTargetPrice":"592.38","Volume":"10707386","HoldingsValue":null,"HoldingsValueRealtime":null,"YearRange":"385.10 - 575.14","DaysValueChange":"- - -0.96%","DaysValueChangeRealtime":"N/A - N/A","StockExchange":"NasdaqNM","DividendYield":"2.24","PercentChange":"-0.96%"}]}}}

As you can see, this is not easily readable. Parsing this JSON result and trying to extract useful information from it is not a straight forward task. Here is one way to make your live easier.

Create a HTML file (name it StockPrices.html) and add in the following code:

<html>
    <script>
function getStockPrice() {
    var req = new XMLHttpRequest();
    req.open('GET',
'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', true);
    req.onload = function(e) {
        if (req.readyState == 4 && req.status == 200) {
            if(req.status == 200) {
                var response = JSON.parse(req.responseText);
                alert("Set breakpoint here");
            } else {
                console.log("Error");
            }
        }
    }
    req.send(null);
}
    </script>
        <body onload="getStockPrice()"></body>
</html>

Essentially, the Javascript code uses the XMLHttpRequest() object to query the Yahoo API service. When the result is returned, you use the JSON.parse() method to convert the JSON string into a JSON object. The challenge would be to discover the various properties and objects contained within this JSON object.

For this, you can use the Chrome browser (you can also use Safari on the Mac). When Chrome is loaded, click on the button on the right-side of the window and select Tools | Developer Tools:



In Chrome, load the StockPrices.html document that you have just created.

At the bottom of the screen, click on the Sources tab:



Click on the Show navigator button:



You will now see the Navigator. Select the StockPrices.html file:


  
The content of StockPrices.html will now be displayed. Clicking on the line number column will set a breakpoint at the particular line:



In this case, you want to set a breakpoint after the response from the Web service has been parsed to a JSON object.

Reload the page to run the script again so that the debugger can now stop at the breakpoint:



On the right-side of the window, expand on the response variable and notice that it has several layers of properties. Expand each layer and look for the information that you want. In this case, we are looking for the stock symbol and bid price. Observe that the response object has a query object, which in turn contains the results object. The results object contains the quote array, which contains two objects. You can now see that the first object has a property named Bid, which is the bidding price of the stock. As you scroll down, you will be able to find the symbol property, which is the symbol for the stock:



You can now add in the following snippets of code to retrieve the stock and bid price of Yahoo and Apple:

<html>
    <script>      
function getStockPrice() {
    var req = new XMLHttpRequest();
    req.open('GET',
'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', true);
    req.onload = function(e) {
        if (req.readyState == 4 && req.status == 200) {
            if(req.status == 200) {
                var response = JSON.parse(req.responseText);
                //alert("Set breakpoint here");
                for (i=0; i<response.query.count; i++) {                      
                   alert(
                      response.query.results.quote[i].Symbol +
                      " - $" +                          
                      response.query.results.quote[i].Bid);                    
                }
            } else {
                console.log("Error");
            }
        }
    }
    req.send(null);
}
    </script>
        <body onload="getStockPrice()"></body>
</html>

Reload the HTML page without the breakpoint. You should now see the price of the stocks you want:


No comments: