Keith
Keith

Reputation: 673

Parsing a JSON feed from YQL using jQuery

I am using YQL's query.multi to grab multiple feeds so I can parse a single JSON feed with jQuery and reduce the number of connections I'm making. In order to parse a single feed, I need to be able to check the type of result (photo, item, entry, etc) so I can pull out items in specific ways. Because of the way the items are nested within the JSON feed, I'm not sure the best way to loop through the results and check the type and then loop through the items to display them.

Here is a YQL (http://developer.yahoo.com/yql/console/) query.multi example and you can see three different result types (entry, photo, and item) and then the items nested within them:

select * from query.multi where queries=
    "select * from twitter.user.timeline where id='twitter';  
     select * from flickr.photos.search where has_geo='true' and text='san francisco';
     select * from delicious.feeds.popular"

or here is the JSON feed itself:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20query.multi%20where%20queries%3D%22select%20*%20from%20flickr.photos.search%20where%20user_id%3D'23433895%40N00'%3Bselect%20*%20from%20delicious.feeds%20where%20username%3D'keith.muth'%3Bselect%20*%20from%20twitter.user.timeline%20where%20id%3D'keithmuth'%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

I am using jQuery's $.getJSON method

Upvotes: 0

Views: 2565

Answers (1)

Fletcher Moore
Fletcher Moore

Reputation: 13804

You don't need to parse JSON by hand. That's the point of JSON. Use JSON.parse(yourJSONstring) to convert it into a Javascript object.

Edit: Actually I'm not sure the browser support for that one. Here's the jQuery way:

http://api.jquery.com/jQuery.parseJSON/

Edit2:

var results = feedObj.query.results.results
for (var i = 0; i < results.length; i++) {
  if (results[i].photo) {
    // do something with photos
  } else if (results[i].item) {
    // do something with items
  } else {
    // do something with entry
  }
}

Test for the existence of the results[i].photo object. If it exists, the result is an array which you can loop through and do something with.

Upvotes: 1

Related Questions