【问题标题】:Search through JSON to find correct 'set', then output value通过 JSON 搜索以找到正确的“集合”,然后输出值
【发布时间】:2012-11-10 02:11:59
【问题描述】:

我目前正在尝试从网站的 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

我希望这已经足够清楚了!

【问题讨论】:

    标签: ruby-on-rails ruby json hash


    【解决方案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
    

    【讨论】:

    • 我已经通过另一种方法保存到数据库的 accountId,这就是我有#{CGI.escape(@summoner.acctId)} 的原因(虽然不确定 CGI.escape 是否正确使用)。我不需要搜索 RankedSolo5x5 来获得 RankedSolo5x5 的 maxRating 吗?因为RankedTeam5x5、RankedTeam3x3等还有其他maxRating。我不确定你把它保存到另一个文件是什么意思?我在 Rails 应用程序中使用它。非常感谢 Deefour,非常感谢!
    • 我已更新我的答案以搜索具有值 'RankedSolo5x5playerStatSummaryType。我没有你的 Rails 应用程序;这就是为什么我把我的答案写成一个独立的 CLI 脚本。我不是建议您在 Rails 应用程序中使用 ARGV[0];那没有意义。
    • 太棒了,非常感谢!对不起我的无知:)
    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 2016-11-02
    • 2012-06-30
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多