On Apr 2, 2009, at 9:27 PM, Chamnap wrote:

>
>
>
> On Apr 2, 3:18 pm, Rob Biedenharn <[email protected]> wrote:
>>
>> Get the JSON gem for starters.
>>
>>    sudo gem install json
>>
>> Then in your code:
>>    require 'rubygems'
>>    gem 'json'
>>    require 'json'
>
> I have followed what you said, but still doesn't work. The params
> variable still contains weird string like: {"{\"first_name\":\"chamnap
> \",\"last_name\":\"chhorn\"}"=>nil, "action"=>"create",
> "controller"=>"users"}. Therefore, I could not access through either
> params[:first_name] or params[:last_name].
>
> Chamnap

irb> require 'rubygems'
=> true
irb> gem 'json'
=> true
irb> require 'json'
=> true
irb> raw = "{\"first_name\":\"chamnap\",\"last_name\":\"chhorn\"}"
=> "{\"first_name\":\"chamnap\",\"last_name\":\"chhorn\"}"
irb> puts raw
{"first_name":"chamnap","last_name":"chhorn"}
=> nil
irb> JSON(raw)
=> {"first_name"=>"chamnap", "last_name"=>"chhorn"}
irb> cooked = JSON.parse(raw)
=> {"first_name"=>"chamnap", "last_name"=>"chhorn"}
irb> raw
=> "{\"first_name\":\"chamnap\",\"last_name\":\"chhorn\"}"
irb> cooked
=> {"first_name"=>"chamnap", "last_name"=>"chhorn"}
irb> raw.class
=> String
irb> cooked.class
=> Hash
irb> cooked["first_name"]
=> "chamnap"
irb> cooked[:first_name]
=> nil

Note that JSON.parse is going to return a normal Ruby Hash, not a  
Rails ActiveSupport HashWithIndifferentAccess.  You'll have to use  
"first_name" as the key, not :first_name. Show the code that you're  
trying to use that's pulling that whole string into a key of the  
params hash.

-Rob

Rob Biedenharn          http://agileconsultingllc.com
[email protected]


--~--~---------~--~----~------------~-------~--~----~
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 [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to