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.

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']