convert ruby hash to URL query string … without those square brackets

后端 未结 5 1769
遇见更好的自我
遇见更好的自我 2021-02-13 16:46

In Python, I can do this:

>>> import urlparse, urllib
>>> q = urlparse.parse_qsl(\"a=b&a=c&d=e\")
>>> urllib.urlencode(q)
\'a=         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 17:24

    Quick Hash to a URL Query Trick :

    "http://www.example.com?" + { language: "ruby", status: "awesome" }.to_query
    
    # => "http://www.example.com?language=ruby&status=awesome"
    

    Want to do it in reverse? Use CGI.parse:

    require 'cgi' 
    # Only needed for IRB, Rails already has this loaded
    
    CGI::parse "language=ruby&status=awesome"
    
    # => {"language"=>["ruby"], "status"=>["awesome"]} 
    

提交回复
热议问题