【问题标题】:How to convert xml response into json and get the value from that json in Ruby on Rails?如何将 xml 响应转换为 json 并在 Ruby on Rails 中从该 json 获取值?
【发布时间】:2017-05-05 14:25:54
【问题描述】:

如何将 xml 响应转换为 json 并从中获取特定值。 这是我尝试过的:

response = HTTParty.post 'http://api.ontraport.com/cdata.php',
{:body => {:appid => 'YeBz0j1',:key => 'NqweN80',:reqType => "fetch_sequences" }}
response = Hash.from_xml(response).to_json
render json: (response)

我得到了结果:

{"result":{"sequence":[{"id":"148"},{"id":"211"},"!Kyle OP Test","(SS) AnikSIB - 1 Hour Reminder","(SS) AnikSIB - 5 minutes Reminder","(SS) AnikSIB - Attended After Over"]}}

但是如果我写render json: (response['result']),那么我的输出是错误的,它只是打印result作为输出。我怎样才能使用JSON.pretty_generate进行漂亮的打印。

【问题讨论】:

    标签: ruby-on-rails json ruby xml


    【解决方案1】:

    你应该首先处理哈希:

    response = Hash.from_xml(response)
    

    NB: 在您的代码 Hash.from_xml(response).to_json 中生成了包含相应 json 的字符串。现在您可以:

    render json: response['result']
    

    render中不需要显式调用to_json,引擎会自行转换。

    旁注: responce['result'] 打印 "result" 字符串是调用 String#[] 方法的一个有趣的副作用。在to_json之后,response包含了string,其中的hash转换为json,由于其中出现了"result"子字符串,所以打印出子字符串。

    【讨论】:

      猜你喜欢
      • 2017-05-05
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2015-02-24
      • 1970-01-01
      • 2011-05-15
      相关资源
      最近更新 更多