在Python中,我可以这样做:
>>> import urlparse, urllib
>>> q = urlparse.parse_qsl("a=b&a=c&d=e")
>>> urllib.urlencode(q)
'a=b&a=c&d=e'
Run Code Online (Sandbox Code Playgroud)
在Ruby [+ Rails]中,我无法弄清楚如何在没有"滚动我自己"的情况下做同样的事情,这看起来很奇怪.Rails方式对我不起作用 - 它为查询参数的名称添加方括号,另一端的服务器可能支持也可能不支持:
>> q = CGI.parse("a=b&a=c&d=e")
=> {"a"=>["b", "c"], "d"=>["e"]}
>> q.to_params
=> "a[]=b&a[]=c&d[]=e"
Run Code Online (Sandbox Code Playgroud)
我的用例很简单,我希望使用query-stringURL部分中某些值的值.依靠标准库和/或Rails似乎很自然,写下这样的东西:
uri = URI.parse("http://example.com/foo?a=b&a=c&d=e")
q = CGI.parse(uri.query)
q.delete("d")
q["a"] << "d"
uri.query = q.to_params # should be to_param or to_query instead?
puts Net::HTTP.get_response(uri)
Run Code Online (Sandbox Code Playgroud)
但只有在结果URI实际上是http://example.com/foo?a=b&a=c&a=d,而不是http://example.com/foo?a[]=b&a[]=c&a[]=d.有没有正确或更好的方法来做到这一点?