0

I have this in my html file:

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

The error returned on Chrome's debugger : Uncaught TypeError: Cannot read property 'count' of undefined

Here is the jfiddle : http://jsfiddle.net/P6nMv/

Here is a snippet of the JSON return object : enter image description here

**Question is why is it undefined when i am parsing it correctly via **jsonReturn.query.count

bouncingHippo
  • 5,940
  • 21
  • 67
  • 107

1 Answers1

2

You're trying to access the URL string as if it were an object. Nowhere do you actually retrieve the data at that URL, parse it, and assign it to an object.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • faux pas indeed. how do i get the JSON object then? – bouncingHippo Nov 20 '12 at 20:31
  • @bouncingHippo, I assume this is a web page, and not something server-side. If that is the case, then you have a cross-origin problem. You can use CORS (limited browser capability), JSON-P (quirky, but will work with anything), or make a server-side proxy so you can use XHR requests. I don't know if Yahoo! supports CORS or JSON-P. Find out. JSON-P is probably the way to go, if it is available. If you end up doing XHR, check out https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest. – Brad Nov 20 '12 at 20:34
  • @bouncingHippo, It looks like Yahoo! does support JSON-P. http://stackoverflow.com/questions/9237593/using-the-yahoo-weather-api-with-json-and-the-script-tag – Brad Nov 20 '12 at 20:35
  • wow i learnt something new today! is there a downside to using CORS because i'll mainly use this web page in Chrome – bouncingHippo Nov 20 '12 at 20:39
  • @bouncingHippo, The downside is limited browser compatibility, particularly with Internet Explorer. If this isn't a problem for you, go for it. Also, I just checked and Yahoo! is supporting CORS, with the following header: `Access-Control-Allow-Origin:*` – Brad Nov 20 '12 at 20:43