我正在调用一个返回JSON对象数组的API,我似乎无法正确访问每个元素。这是API调用的示例返回值
[{"param1":1,"param2":"blah1"},
{"param1":2,"param2":"blah2"},
{"param1":3,"param2":"blah3"}]
这是我尝试调用API并打印第一个JSON响应对象的参数
result = HTTParty.get('http://randomapi.com',query: options)
@a = result[0]['param1']
# puts "#{result}"
puts "#{@a}"
这样做什么都不打印。我知道我已成功访问该URL,因为结果将打印正确的信息。
我获得了有关如何通过此URL访问JSON响应的信息 http://blog.teamtreehouse.com/its-time-to-httparty
修改: 在阅读下面的评论之后,我意识到API调用正在返回text / html的内容类型,并且解析text / html不起作用,因为响应也在预期值之下返回以下标题。有没有办法删除它而不进入字符串本身并剥离它?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form method="post" action="GetRankingList.aspx?pvptype=1&sid=1&tm=20130821160000&auth=77c9b582c3aed3d3974400cfb118fe4b" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZLSAAAtd4/lj1u6b0GjPWM+p3i9tqI6sq+xDrRw2cAv3" />
</div>
<div></div>
</form>
</body>
</html>
答案 0 :(得分:1)
似乎API返回的响应 Content-Type 与 application / json 不同。您可以通过打印来检查:
puts result.content_type
如果是这样, HTTParty 解析器可能会将响应解释为纯文本;因此,代码result[0]['param1']
评估为nil
也许您可以尝试使用以下内容将所需值解析为@a
:
@a = JSON.parse(result)[0]['param1']
不要忘记要求json库
require 'json'
祝你好运!
答案 1 :(得分:0)
以格式
访问json时require 'json'
result = JSON.parse('[{"param1":1,"param2":"blah1"},{"param1":2,"param2":"blah2"}, {"param1":3,"param2":"blah3"}]')
@a = result[0]["param1"]
puts @a
答案 2 :(得分:0)
您需要从结果中解析 parsed_response 。
@parsed = JSON.parse(result.parsed_response)