如何将xml响应转换为json并从Ruby on Rails中的json获取值?

时间:2016-12-20 11:21:21

标签: ruby-on-rails json ruby xml

如何将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进行漂亮的打印。

1 个答案:

答案 0 :(得分:0)

你应该首先处理哈希:

response = Hash.from_xml(response)
代码Hash.from_xml(response).to_json中的

NB:生成了包含相应json的字符串。现在你可以:

render json: response['result']

一个人不需要在to_json中明确调用render,引擎会自行转换它。

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