Ruby:如何将哈希转换为 HTTP 参数? [英] Ruby: How to turn a hash into HTTP parameters?
本文介绍了Ruby:如何将哈希转换为 HTTP 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用像
{:a => "a", :b => "b"}
这将转化为
"a=a&b=b"
但是你怎么处理像
{:a => "a", :b => ["c", "d", "e"]}
应该翻译成
"a=a&b[0]=c&b[1]=d&b[2]=e"
或者更糟的是,(做什么)像这样:
Or even worse, (what to do) with something like:
{:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]
非常感谢您的帮助!
推荐答案
更新:此功能已从 gem 中删除.
Update: This functionality was removed from the gem.
Julien,你的自我回答很好,我无耻地借鉴了它,但它没有正确地转义保留字符,而且还有一些其他的边缘情况会失效.
Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.
require "addressable/uri"
uri = Addressable::URI.new
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
uri.query
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
uri.query
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
uri.query
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
uri.query
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
uri.query
# => "a=a&b[c]=c&b[d]"
宝石是'可寻址'
gem install addressable
这篇关于Ruby:如何将哈希转换为 HTTP 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文