Json => hash in Ruby

Hi everyone,

I would like to decode a json string and transform it into a hash in
ruby.
I tried

json = “{“userid” : “21”, “friendid” : “9”}”
hash = ActiveSupport::JSON.decode(json)
puts hash[:userid]

however, this gives NIL back. How do I have to do this?

Thanks for any help!

Try hash[“userid”] instead.

You can only have interchangeable strings and symbols if it is a
HashWithIndifferentAccess, like params and flash from Rails. By the
looks of
that, it’s creating just a Hash.

On Fri, Apr 25, 2008 at 9:06 PM, Martin [email protected] wrote:

however, this gives NIL back. How do I have to do this?

Thanks for any help!


Ryan B.

Feel free to add me to MSN and/or GTalk as this email.

json = “{“userid” : “21”, “friendid” : “9”}”
hash = ActiveSupport::JSON.decode(json).symbolize_keys
puts hash[:userid]

Note the symbolize keys which will make it work as expected with the
keys as symbols. By default, the keys are strings:

puts hash[‘userid’]