我了解如何決議 JSON,但如果它包含指向其他頁面的鏈接,我不明白如何決議它。
我將不勝感激您的幫助!
api.example.com/v0/accounts
在對 JSON 檔案的第一個請求中,我們得到:
{
"response": "OK",
"nfts": [
{
"token_id": "35507806371588763669298464310896317145981867843055556101069010709538683224114"
}
],
"total": null,
"continuation": "1634866413000"
}
有一行:continuation,它是到下一個請求的鏈接,因此它重復了很多次。
在下一個請求時,鏈接更改為 api.example.com/v0/accounts&continuation=1634866413000
我的代碼現在看起來像這樣:
class Source
include Mongoid::Document
include Mongoid::Timestamps
require 'json'
after_save :add_items
def add_items
json= HTTParty.get("https://api.example.com/v0/accounts")
json.dig('nfts')
load_items_ethereum.each do |item|
Item.create!(
:token_id => item['token_id'],
)
end
end
end
uj5u.com熱心網友回復:
像 HTTParty 這樣的低級 HTTP 客戶端通常不處理迭代。你需要自己做,使用回圈直到沒有延續欄位,例如:
begin
continuation_param = "?continuation=#{continuation_id}" if continuation_id
json = HTTParty.get("https://api.example.com/v0/accounts#{continuation_param}")
continuation_id = json.dig('continuation');
# process latest payload, append it to a running list, etc.
end while continuation_id
(對于生產,最佳實踐是保留一個計數器,以便您可以在 N 次迭代后保釋,以避免無限回圈。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378402.html
