Help me decode JSON response

51 views
Skip to first unread message

binaryMoods

unread,
Nov 27, 2015, 5:33:51 PM11/27/15
to AngularJS
Angular Developer Guide https://docs.angularjs.org/guide/concepts

So this is the url: var YAHOO_FINANCE_URL_PATTERN =  '//query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("PAIRS")&format=json&env=store://datatables.org/alltableswithkeys&callback=JSON_CALLBACK';

If you run it it will return the following (PAIRS above is USDEUR):

/**/JSON_CALLBACK({"query":{"count":1,"created":"2015-11-27T22:10:34Z","lang":"en-US","results":{"rate":{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9440","Date":"11/27/2015","Time":"10:10pm","Ask":"0.9443","Bid":"0.9440"}}}});

This is the code that processes Json:

var url = YAHOO_FINANCE_URL_PATTERN.
               replace('PAIRS', 'USD' + currencies.join('","USD'));
              
    return $http.jsonp(url).then(function(response) {
      var newUsdToForeignRates = {};
      angular.forEach(response.data.query.results.rate, function(rate) {
        var currency = rate.id.substring(3,6);
        newUsdToForeignRates[currency] = window.parseFloat(rate.Rate);
      });

Here is the plunker, code is in finance3.js: http://plnkr.co/edit/m3K11e6KItx6HwfCCHCo?p=preview

I can see query, results, rate etc in the JSON file AND in the code, but the code also has - response and data.

(1) Is the whole JSON treated as 'response' and where does data come from (its not in JSON file)?
(2) What do you do with this piece -> /**/JSON_CALLBACK?

Sander Elias

unread,
Nov 27, 2015, 10:57:36 PM11/27/15
to AngularJS
Hi binaryMoods,

No, you do receive the response, not the json. The response is everything around your request (redears,config,uri and data). the stuff you need is inside data.
I use a construct like this most of the time:

function Yahou_fin($http) {

   
var url = YAHOO_FINANCE_URL_PATTERN.               replace('PAIRS', 'USD' + currencies.join('","USD'));
               
   
return $http
       
.jsonp(url)

       
.then(resp => resp.data)  //es6 arrow function supported in all browsers I care about.
       
.then(data => {
           data
.query.results.rate.reduce((newUsdToForeignRates, rate) => {newUsdToForeignRates[rate.id.substring(3,6)]=window.parseFloat(rate.Rate);},{})
       
})
       
;

}

You plunker seems to miss angular and yahoo script. I have no time now to fix it.

Oh, and you last question, that's just how JSONP works, and is there for your protection. 

Regards
Sander

binaryMoods

unread,
Nov 28, 2015, 2:58:41 PM11/28/15
to AngularJS
Hi Sander,

Thank you! Yea, no worries, it's from Angular JS developer guide, and I don't care if it works, but thanks for trying.

I was just trying to understand how to extract stuff from response.
Reply all
Reply to author
Forward
0 new messages