Search code examples
ruby-on-railsjsonrubyriot-games-apiruby-hash

How can I extract a Summoner Name from a JSON response?


I'm playing around with with external APIs from League of Legends. So far, I've been able to get a response from the API, which returns a JSON object.

 @test_summoner_name = ERB::Util.url_encode('Jimbo')
 @url = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/#{@test_summoner_name}?api_key=#{RIOT_API_KEY}"
 response = HTTParty.get(@url)
 @summoner = JSON.parse(response.body)
 @summoner_name = @summoner[:name]

The JSON object looks like this:

{"jimbo"=>{"id"=>12345678, "name"=>"Jimbo", "profileIconId"=>1234, "revisionDate"=>123456789012, "summonerLevel"=>10}}

So, I'm able to output the JSON object with my @summoner variable in my view. But when I try to output my @summoner_name variable, I just get a blank string.

For reference, this is my view currently:

Summoner Object: <%= @summoner %><br>

Summoner Name: <%= @summoner_name %>

Any help would be greatly appreciated. I've been stumbling through this process all day now.


Solution

  • Problem

    You don't have the hash you think you do. Once you've parsed your JSON, your @summoner instance variable actually contains everything else wrapped under a hash key named jimbo. For example, when using the awesome_print gem to pretty-print your hash, you will see:

    require 'awesome_print'
    ap @summoner, indent: 2, index: false
    
    {
      "jimbo" => {
                   "id" => 12345678,
                 "name" => "Jimbo",
        "profileIconId" => 1234,
         "revisionDate" => 123456789012,
        "summonerLevel" => 10
      }
    }
    

    Solution

    To get at the name key, you have to go deeper into the hash. For example, you can use Hash#dig like so:

    @summoner_name = @summoner.dig 'jimbo', 'name'
    #=> "Jimbo"
    

    If you're using an older Ruby without the Hash#dig method, then you can still get at the value by specifying a sub-key as follows:

    @summoner_name = @summoner['jimbo']['name']
    #=> "Jimbo"