1

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Xadren
  • 315
  • 4
  • 16
  • I suggest you read a basic tutorial about ruby hashes. http://rubylearning.com/satishtalim/ruby_hashes.html – Roman Kiselenko Apr 30 '17 at 11:02
  • @Зелёный In fairness to the OP, this is a good question because JSON sometimes wraps responses, which is *not* always self-evident to API consumers. Nested (but similarly-named) keys are a common problem with JSON. – Todd A. Jacobs May 01 '17 at 14:07

2 Answers2

2

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"
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 1
    This is great thanks. Alejandro's response was incredibly helpful, but your line about Hash#dig looks much more appealing to me. I'll be sure to look into using that. – Xadren May 01 '17 at 06:11
1

It migth help if you look your json like this:

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

Then you could just do

@summoner_jimbo_name = @summoner['jimbo']['name']

to get the value:

Jimbo

Alejandro Montilla
  • 2,626
  • 3
  • 31
  • 35