0

我已经成功地对 Facebook、Twitter 和 LastFM 进行了 API 调用,以使用以下代码检索 Likes、Followers 和 Listeners:

 def get_twitter
    @artist = Artist.accessible_by(current_ability).find(params[:id])
    if @artist.twitter_screen_name.present?
      require 'open-uri'
      require 'json'
      result = JSON.parse(open("https://api.twitter.com/1/users/show.json?screen_name="<<@artist.twitter_screen_name<<"&include_entities=true").read)
      @followers = result["followers_count"]
    end
  end    

这很好用,因为只返回一个数据集,并且很容易访问我想要的位。LastFM 的响应是嵌套的,虽然它抛出了我,但我设法访问了与上面几乎完全相同的 Listeners 计数,但只使用了以下行:

@listeners = result["artist"]["stats"]["listeners"].to_i

现在,我正在尝试从 Songkick 检索事件列表。显然,响应包含多个事件,因此我无法知道如何遍历响应。

他们的开发者指南在这里: http: //www.songkick.com/developer/upcoming-events-for-artist

示例响应如下,但这仅适用于单个事件:

{
  "resultsPage:" {
    "results": { "event": [
      {
        "id":11129128,
        "type":"Concert",
        "uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
        "displayName":"Wild Flag at The Fillmore (April 18, 2012)",
        "start":{"time":"20:00:00",
                 "date":"2012-04-18",
                 "datetime":"2012-04-18T20:00:00-0800"},
        "performance":[{"artist":{"uri":"http://www.songkick.com/artists/29835-wild-flag?utm_source=PARTNER_ID&utm_medium=partner",
                                  "displayName":"Wild Flag","id":29835,"identifier":[]},
                        "displayName":"Wild Flag",
                        "billingIndex":1,
                        "id":21579303,
                        "billing":"headline"}],
        "location":{"city":"San Francisco, CA, US","lng":-122.4332937,"lat":37.7842398},
        "venue":{"id":6239,
                 "displayName":"The Fillmore",
                 "uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
                 "lng":-122.4332937, "lat":37.7842398,
                 "metroArea":{"uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
                              "displayName":"SF Bay Area","country":{"displayName":"US"},"id":26330,"state":{"displayName":"CA"}}},
        "status":"ok",
        "popularity":0.012763
      }, ....
    ]},
    "totalEntries":24,
    "perPage":50,
    "page":1,
    "status":"ok"
  }
}

有没有人有任何指示?

4

1 回答 1

1

您只需要进入数组并迭代:

parsed = JSON.parse(some_json)
events = parsed['resultsPage']['results']['event']
events.each do |event|
  puts event["type"]
  #access other parts of the event
end
于 2012-07-15T01:57:43.680 回答