2

I'm working with the Steam Storefront API - http://store.steampowered.com/api/appdetails/?appids=240

I've parsed the JSON into a hash.

When I try to select any hash value nested inside of "data" I receive an "undefined method `[]' for nil:NilClass" error.

I can puts the whole lot with res["240"]["data"] which shows me all of the keys and values. All of which seem to look fine.

However when I try to go one branch further it throws nil.

res["240"]["data"]["type"]

Using .key also throws up an error.

res["240"]["data"].key

My quest to find an answer has mainly found suggestions of searching for the key & values, however I know the direct route to the data so I'd like to go this route if possible.

Thanks.

3 Answers 3

5

If you're on ruby 2.3, you may use dig, as suggested by @sawa.

http://docs.ruby-lang.org/en/2.3.0/Hash.html#method-i-dig

However, if you are not on ruby 2.3, then things get a bit trickier.

The simplest approach is to implement your own version of dig:

class Hash
  def dig(*path)
    path.inject(self) do |h, k|
      h.respond_to?(:keys) ? h[k] : nil
    end
  end
end

Then you can just res.dig("240", "data", "type")

Sign up to request clarification or add additional context in comments.

1 Comment

@sawa answer works, however thank you for taking into consideration I might not have had 2.3 yet. It's rather lucky they released "dig" just before I needed it :)
4

You can use dig in combination with the safe navigation operator, like:

res&.dig("240", "data", "type")

If res is nil (or more accurately isn't "digable") then it will return nil instead of raising.

Comments

1

Use dig.

res.dig("240", "data", "type")

4 Comments

nil does not implement .dig: [3] pry(main)> nil.dig("240", "data", "type") NoMethodError: undefined method 'dig' for nil:NilClass
@tomsabin So what? How is that relevant to the question?
My misunderstanding of the question - thinking that res was originally nil.
Quote from the question: "I've parsed the JSON into a hash."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.