【问题标题】:How to access multiple key-value in URI如何访问 URI 中的多个键值
【发布时间】:2017-06-19 07:03:14
【问题描述】:

我遇到了一个场景,我需要多个相同字段类型的输入来呈现一个表单。

给出一些上下文:

GET post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India

我需要分别返回品牌"bmw"的型号和国家"India"的城市。

结构基于“How to design REST URI for multiple Key-Value params of HTTP GET

如何访问params['tree_field']

【问题讨论】:

标签: ruby web-services api


【解决方案1】:

您可以结合URI#parseCGI#parse 来获取参数:

require 'cgi'
require 'uri'
url = 'post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India'
queries = CGI.parse(URI.parse(url).query)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}
queries['tree_field'] #=> ["brand", "country"]

但是,如果您只是在字符串中包含参数,那么您可以使用 CGI#parse:

params = 'tree_field=brand;brand=bmw&tree_field=country;country=India'
CGI.parse(params)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}

【讨论】:

  • 谢谢@surya。我正在使用 sinatra gem。好吧,这很好,但对于我正在工作的项目,我不想使用CGI
  • 仅供参考:cgi 和 uri 是 Ruby 中的标准库。
  • 谢谢,我知道。我的意思是我不允许使用 cgi gem。
  • 如果你不能使用 CGI gem 那么为什么选择这个作为答案呢?
【解决方案2】:

您的问题不清楚,但也许这会有所帮助:

require 'uri'

uri = URI.parse('http://somehost.com/post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India')
query = URI.decode_www_form(uri.query).map{ |a| a.last[/;(.+)$/, 1].split('=') }.to_h # => {"brand"=>"bmw", "country"=>"India"}

分解为:

query = URI.decode_www_form(uri.query)       # => [["tree_field", "brand;brand=bmw"], ["tree_field", "country;country=India"]]
  .map{ |a| a.last[/;(.+)$/, 1].split('=') } # => [["brand", "bmw"], ["country", "India"]]
  .to_h                                      # => {"brand"=>"bmw", "country"=>"India"}

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多