搜索JSON以找到正确的'set',然后输出值

时间:2012-11-10 02:11:59

标签: ruby-on-rails ruby json hash

我目前正试图从网站的API JSON输出中提取信息。 这就是我所拥有的,它几乎完美无缺:

def get_player_stats
  uri = URI("http://elophant.com/api/v1/euw/getPlayerStats?accountId=#{CGI.escape(@summoner.acctId)}&season=CURRENT&key=KEYID")
  resp = Net::HTTP.get_response(uri)
  hash = JSON(resp.body)

  solo_ranked_elo = hash['playerStatSummaries']['playerStatSummarySet'][2]['maxRating']
  puts solo_ranked_elo

end

问题是['playerStatSummarySet'][1]值会根据播放器而改变。因此,对于一个玩家,他们的maxRating将设置为[1],而另一个玩家的maxRating将设置为[6]

我需要搜索RankedSolo5x5值存在的集合,然后我可以输出maxRating。我该怎么做?

以下是我用于比较的两个示例文件:

http://elophant.com/api/v1/euw/getPlayerStats?accountId=22031699&season=CURRENT&key=KEYID

http://elophant.com/api/v1/euw/getPlayerStats?accountId=23529170&season=CURRENT&key=KEYID

我希望这很清楚!

1 个答案:

答案 0 :(得分:1)

这是一个完整的例子

#!/usr/bin/env ruby

require 'net/http'
require 'uri'
require 'json'

uri = URI("http://elophant.com/api/v1/euw/getPlayerStats?accountId=#{ARGV[0]}&season=CURRENT&key=KEYID")
resp = Net::HTTP.get_response(uri)
stat_summary = JSON(resp.body)['playerStatSummaries']['playerStatSummarySet']

stat_summary.each_with_index do |obj, i| # it's this loop that answers your question
  next if obj['playerStatSummaryType'] != 'RankedSolo5x5'

  puts obj['maxRating']
  break
end

ARGV[0]accountID的命令行参数值。您将上述内容保存到某个max_rating文件chmod +x max_rating,然后运行

./max_rating 22031699       # Outputs 1421
./max_rating 23529170       # Outputs 1237