用jquery解析yahoo API json时遇到问题

时间:2010-07-04 01:40:57

标签: jquery json api parsing yahoo

我在解析以下链接时遇到问题。我希望能够使用$ .getJSON()从数组中的每个对象中提取一些对象特征。有谁知道如何做到这一点?

谢谢!

  

http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid=YahooDemo&query=market&results=2&language=en&output=json&callback=

这是实际的对象:

{"ResultSet":{"totalResultsAvailable":"68369","totalResultsReturned":2,"firstResultPosition":"1","Result":[{"Title":"MARKET SNAPSHOT: U.S. Stocks To Begin New Week In Vulnerable Spot","Summary":"MARKET SNAPSHOT: U.S. Stocks To Begin New Week In Vulnerable Spot","Url":"http:\/\/www.foxbusiness.com\/story\/markets\/industries\/market-snapshot-stocks-begin-new-week-vulnerable-spot\/","ClickUrl":"http:\/\/www.foxbusiness.com\/story\/markets\/industries\/market-snapshot-stocks-begin-new-week-vulnerable-spot\/","NewsSource":"FOX Business","NewsSourceUrl":"http:\/\/www.foxbusiness.com\/","Language":"en","PublishDate":"1278143248","ModificationDate":"1278144826"},{"Title":"MARKET SNAPSHOT: U.S. Stocks In The Red, Post Weekly Losses","Summary":"MARKET SNAPSHOT: U.S. Stocks In The Red, Post Weekly Losses","Url":"http:\/\/feeds.foxbusiness.com\/~r\/foxbusiness\/latest\/~3\/hL3f6RiYhdU\/","ClickUrl":"http:\/\/feeds.foxbusiness.com\/~r\/foxbusiness\/latest\/~3\/hL3f6RiYhdU\/","NewsSource":"Fox News","NewsSourceUrl":"http:\/\/www.foxnews.com\/","Language":"en","PublishDate":"1278109361","ModificationDate":"1278109412"}]}}

2 个答案:

答案 0 :(得分:1)

以下内容应该有效。您需要从数据中提取所需的属性

$.getJSON('http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid=YahooDemo&query=market&results=2&language=en&output=json&callback=', function(data) {
  alert(data.ResultSet.totalResultsAvailable);
});

更新

输出有意义的结果,成功函数需要回调。

答案 1 :(得分:1)

我不确定我是否完全了解它,但如果你仔细阅读,你会看到它是对象符号(毕竟这是JSON的意思),所以你可以访问任何具有限定名称的属性(数据。 ResultSet.Result [0] .Summary将访问第一个结果的摘要,例如)。

无论如何,您要提取哪些特征?您想将它们打印到某个DOM组件,提醒它们还是将它们存储在变量中?无论如何,请检查以下代码:对于每个结果,它将在警告对话框中打印它的标题和URL(它使用jQuery的每个函数来迭代结果):

$.getJSON('http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid=YahooDemo&query=market&results=2&language=en&output=json&callback=',
function(data){
   $.each(data.ResultSet.Result, function(index, value){
     alert("Result #"+index+": "+value.Title+" url: "+value.Url);
   });
   return false;
});

我会留下回调,因为它可能是一个跨站点调用,并且该参数用于规避大多数主流浏览器强制执行的相同原始策略。