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!
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---
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 <mjdgard-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> > 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! > > >-- Ryan Bigg http://www.frozenplague.net Feel free to add me to MSN and/or GTalk as this email. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
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'']
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---