I have a json response like this:
@response = {"result":{"amount":0.0}}
How can I get the value of amount into a variable?
I've tried:
@response['result']['amount']
@response['result'][0]
@response[0][0]
I'm using the json gem.
I have a json response like this:
@response = {"result":{"amount":0.0}}
How can I get the value of amount into a variable?
I've tried:
@response['result']['amount']
@response['result'][0]
@response[0][0]
I'm using the json gem.
Try this
@response[:result][:amount]
the keys in @response
object are :symbols
not strings
For more info: What's the difference between a string and a symbol in Ruby?
With nested Hashes Ruby's Hash#dig
method is very handy since it is returning nil if any intermediate step is nil.
@response.dig(:result, :amount)
If you are not sure is the key string or symbol you can use ActiveSupport::HashWithIndifferentAccess that provides Hash#with_indifferent_access
(Rails will include this by default). Then you can get the value with both symbol and string formatted key.