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.
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With