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

时间:2021-09-07 23:45:04

How can I convert the xml responce into json and get the particular value from it. Here is what I tried :

如何将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)

And I am getting the result:

我得到的结果是:

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

But I if write render json: (response['result']) then my output is wrong it just print result as output.And how can I use JSON.pretty_generate for pretty print.

但我如果写渲染json :(响应['结果'])然后我的输出是错误的它只是打印结果作为输出。我怎么能使用JSON.pretty_generate进行漂亮的打印。

1 个解决方案

#1


0  

You should deal with the hash in the first place:

你应该首先处理哈希:

response = Hash.from_xml(response)

NB: in your code Hash.from_xml(response).to_json had produced the string, containing the respective json. Now you can:

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

render json: response['result']

One does not need to explicitly call to_json in render, the engine will convert it on it’s own.

一个不需要在渲染中显式调用to_json,引擎将自己转换它。

Sidenote: responce['result'] printing "result" string is a funny side-effect of a call to String#[] method. After to_json, response contains the string with a hash converted to json, and since there is an occurrence of "result" substring in it, the substring is printed out.

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

#1


0  

You should deal with the hash in the first place:

你应该首先处理哈希:

response = Hash.from_xml(response)

NB: in your code Hash.from_xml(response).to_json had produced the string, containing the respective json. Now you can:

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

render json: response['result']

One does not need to explicitly call to_json in render, the engine will convert it on it’s own.

一个不需要在渲染中显式调用to_json,引擎将自己转换它。

Sidenote: responce['result'] printing "result" string is a funny side-effect of a call to String#[] method. After to_json, response contains the string with a hash converted to json, and since there is an occurrence of "result" substring in it, the substring is printed out.

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