Rod*_*igo 15 ruby-on-rails ruby-on-rails-3
我使用一些返回xml的服务:
response = HTTParty.post(service_url)
response.parsed_response
=> "\n\t<Result>\n<success>\ntrue\n</success>\n</Result>"
Run Code Online (Sandbox Code Playgroud)
我需要将此字符串转换为哈希值.像这样的东西:
response.parsed_response.to_hash
=> {:result => { :success => true } }
Run Code Online (Sandbox Code Playgroud)
这样做的方法是什么?
zea*_*soi 35
内置的from_xmlRails Hash方法将完全符合您的要求.为了response.parsed_response正确映射到哈希,您需要gsub()输出换行符:
hash = Hash.from_xml(response.parsed_response.gsub("\n", ""))
hash #=> {"Result"=>{"success"=>"true"}}
Run Code Online (Sandbox Code Playgroud)
在解析中的Rails散列的情况下,对象String类型是不实质性不同比那些Symbol从一般的编程的角度.但是,您可以将Rails symbolize_keys方法应用于输出:
symbolized_hash = hash.symbolize_keys
#=> {:Result=>{"success"=>"true"}}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,symbolize_keys不会对任何嵌套哈希进行操作,但您可能会迭代内部哈希并应用symbolize_keys.
拼图的最后一部分是将字符串转换"true"为布尔值true.AFAIK,没有办法在你的哈希上做到这一点,但如果你正在迭代/操作它,你可能会实现像这篇文章中建议的解决方案:
def to_boolean(str)
return true if str == "true"
return false if str == "false"
return nil
end
Run Code Online (Sandbox Code Playgroud)
基本上,当您到达内部键值对时,您将应用于to_boolean()当前设置为的值"true".在您的示例中,返回值是布尔值true.
Pyt*_*Dev 10
使用nokogiri解析对ruby哈希的XML响应.这很快.
require 'active_support/core_ext/hash' #from_xml
require 'nokogiri'
doc = Nokogiri::XML(response_body)
Hash.from_xml(doc.to_s)
Run Code Online (Sandbox Code Playgroud)
您可以尝试以下操作:
require 'active_support/core_ext/hash/conversions'
str = "\n\t<Result>\n<success>\ntrue\n</success>\n</Result>".gsub("\n", "").downcase
Hash.from_xml(str)
# => {"result"=>{"success"=>"true"}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16541 次 |
| 最近记录: |