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.

nickgryg
  • 25,567
  • 5
  • 77
  • 79
  • I get syntax error with this `@response = {"result":{"amount":0.0}}` – Jagdeep Singh Dec 14 '17 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`. – Jagdeep Singh Dec 14 '17 at 11:17

2 Answers2

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?

Abdullah
  • 2,015
  • 2
  • 20
  • 29
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.

Lauri
  • 4,336
  • 3
  • 18
  • 18