Pratik Bothra
Pratik Bothra

Reputation: 2694

Converting http_params to hash

I can obtain an array from the string

http_params="created_end_date=2013-02-28&created_start_date=2013-01-01&page_size=50&offset=0&order_id=0D1108211501118%0D%0A0D11108211501118%0D%0Ac%0D%0AD%0D%0ADK212071409743%0D%0AKK30109110100%0D%0AKK30111140300%0D%0AKK30111140400%0D%0AKK30115120100%0D%0AKK30115150100&page_number=1"

So I did myarray=http_params.split("&"):

myarray=["created_end_date=2013-02-28", "created_start_date=2013-01-01", "page_size=50", "offset=0", "order_id=0D1108211501118%0D%0A0D11108211501118%0D%0Ac%0D%0AD%0D%0ADK212071409743%0D%0AKK30109110100%0D%0AKK30111140300%0D%0AKK30111140400%0D%0AKK30115120100%0D%0AKK30115150100", "page_number=1"] 

I need to convert this to a hash myhash, so that I can make a Rest Client post call for myhash.to_json. Basically it should be key,value pairs like:

{:created_end_date=>"2013-02-28",:created_start_date=>"2013-01-01"....}

I know that the inverse operation can be done like this:

http_params = myhash.map{|k,v| "#{k}=#{v}"}.join('&')

but I am unable to come up with neat code for this.

What's the best way I should go about this?

Upvotes: 3

Views: 329

Answers (2)

poseid
poseid

Reputation: 7156

With pure Ruby methods, you can convert your string into a Hash as follows:

"a=1&b=2".split('&').map { |h| Hash[*h.split("=")] }
=> [{"a"=>"1"}, {"b"=>"2"}]

A blog post how to operate on Ruby collections is here: http://thinkingonthinking.com/map-reduce-in-ruby/

To get symbols as keys, a small additional step is necessary:

"a=1&b=2".split('&').map { |h| hs = h.split("="); Hash[hs[0].to_sym, hs[1]] }
=> [{:a=>"1"}, {:b=>"2"}]

As last step, a merge of the inner Hash elements has to be done. This can be done like:

"a=1&b=2".split('&').map { |h| hs = h.split("="); Hash[hs[0].to_sym, hs[1]] }.inject({}) { |s, h| s.merge(h) }
=> {:a=>"1", :b=>"2"}

Upvotes: 2

spas
spas

Reputation: 1934

require 'cgi'
hash = CGI::parse http_params

Or you can use:

hash = Rack::Utils.parse_nested_query http_params

Which does not return the values as arrays.

Upvotes: 5

Related Questions