Thursday, April 2, 2009

JSON Handling Request in Rails

I have messed around for almost a day today just to find how to convert from json object to ruby object when posting a REST web service. However, I have known quite well a couple more features of Rails in depth like Migration, Testing, RSpec, ActiveResource,....

There are three data format we can post through AJAX (from JavaScript): serialization, and xml. Serialization is the process that formats a set of data so that the server can easily read
it from javascript object or html form.

// Serialized form
name=Chhorn&last=Chamnap&city=Cambridge&zip=02140

//XML
<name>Chhorn</name>
<last>Chamnap</last>
<city>Cambridge</city>
<zip>02140</zip>

Rails automatically recognizes these format very well. In your controller, you can access from params[:name], params[:last],.... However, you would face difficulties when you do a post request with json object. In your params variable would be {"{\"first_name\":\"chamnap
\",\"last_name\":\"chhorn\"}"=>nil. Therefore, you must parse this string to ruby object. There are two possible solutions. First solution, I got from a discussion.

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

Secondly, I found by chance from my book by using ActiveSupport::JSON.decode() method.

2 comments:

Web Design Company said...

Hi Friend,

Nice to see your Blog.....I Like you Blog.
I am also interested in latest news, sometimes i posted on my blog.....

chamnap said...

Thanks.

Subscribe in a Reader