簡體   English   中英

HTTPArty / Rails:如何處理Response數組

[英]HTTPArty/Rails: How to handle the Response array

我正在調用一個返回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&amp;sid=1&amp;tm=20130821160000&amp;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>

看來該API返回的響應的Content-Typeapplication / json不同。 您可以通過打印來檢查:

puts result.content_type

如果是這樣, HTTParty解析器可能會將響應解釋為純文本; 因此,代碼result[0]['param1']計算結果為nil也許您可以嘗試使用以下方法將所需的值解析為@a

@a = JSON.parse(result)[0]['param1']

別忘了需要json庫

require 'json'

祝好運!

使用格式訪問json時

require 'json'
result = JSON.parse('[{"param1":1,"param2":"blah1"},{"param1":2,"param2":"blah2"}, {"param1":3,"param2":"blah3"}]')
@a = result[0]["param1"]
puts @a

您需要從結果中解析parsed_response

@parsed = JSON.parse(result.parsed_response)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM