Martin11
(Martin)
April 25, 2008, 11:36am
1
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!
radar
(Ryan Bigg)
April 25, 2008, 12:19pm
2
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.
11175
(-- --)
April 25, 2008, 5:23pm
3
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']