如何将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
进行漂亮的打印。
答案 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"
子字符串,因此打印出子字符串