2

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.

2
  • I get syntax error with this @response = {"result":{"amount":0.0}} Commented Dec 14, 2017 at 11:16
  • You can indeed use bracket notation [] to access values from a json response. Just check all the available keys that can be passed into [] by calling @response.keys. Commented Dec 14, 2017 at 11:17

2 Answers 2

1

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?

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.