2013-03-21 107 views
3

我可以从字符串转换http_params哈希

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" 

所以我做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"] 

我需要将其转换为一个哈希myhash,这样我可以做一个Rest客户端发送myhash.to_json调用。基本上,它应该是键,值对喜欢:

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

我知道,反向操作可以这样做:

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

,但我无法想出这个整洁的代码。

我应该怎么做这个最好的方法是什么?

回答

4
require 'cgi' 
hash = CGI::parse http_params 

或者你可以使用:

hash = Rack::Utils.parse_nested_query http_params 

没有返回值作为数组。

+0

就是这样?真的很简单。 :-) – 2013-03-21 14:05:18

+1

键是字符串,但由于某些原因,这些值会变成单个元素数组:“{”created_end_date“=> [”2013-02-28“],”created_start_date“=> [”2013-01-01“ ],...}'。我想知道为什么。 – Mischa 2013-03-21 14:06:24

+0

我想知道同样的事情....当我做hash.to_json时,我得到{\“created_end_date \”:[\“2013-02-28 \”] ...} – 2013-03-21 14:12:03

2

纯Ruby方法,您可以将字符串转换成散列如下:

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

博客文章如何在Ruby的集合进行操作是在这里:http://thinkingonthinking.com/map-reduce-in-ruby/

要得到符号键,需要一小步额外的步骤:

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

作为最后一步,必须完成内部哈希元素的合并。可以这样做:

"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"} 
+0

虽然这似乎不是所需的输出。 – Mischa 2013-03-21 14:08:36

+0

我添加了一个应该显示如何使用to_sym来获取符号键的示例 – poseid 2013-03-21 14:17:38

+0

我并不是在谈论符号与字符串。这将返回一个包含大量散列的数组。他似乎想要一个有很多元素的散列。例如。 '{:a =>'1',:b =>'2'}' – Mischa 2013-03-21 14:18:44