2015-10-04 54 views
2

一直在用Kickbox的api進行電子郵件驗證。我試圖讓程序只在返回的JSON中顯示結果對象。在ruby中訪問第三方API JSON對象

下面的代碼:

require "kickbox" 
require 'httparty' 
require 'json' 


client = Kickbox::Client.new('ac748asdfwef2fbf0e8177786233a6906cd3dcaa') 
kickbox = client.kickbox() 
response = kickbox.verify("[email protected]") 

file = File.read(response) 

json = JSON.parse(file) 

json['result'] 

我得到一個錯誤verify.rb:10:read': no implicit conversion of Kickbox::HttpClient::Response into String (TypeError) from verify.rb:10:in'

下面是一個示例響應:

{ 
    "result":"undeliverable", 
    "reason":"rejected_email", 
    "role":false, 
    "free":false, 
    "disposable":false, 
    "accept_all":false, 
    "did_you_mean":"[email protected]", 
    "sendex":0, 
    "email":"[email protected]", 
    "user":"bill.lumbergh", 
    "domain":"gamil.com", 
    "success":true, 
    "message":null 
} 
+0

對不起 - 這裏的輸出是什麼? – Anthony

回答

1

您收到此錯誤:

read': no implicit conversion of Kickbox::HttpClient::Response into String (TypeError) 

因爲,在這一行:

file = File.read(response) 

responseKickbox::HttpClient::Response類型的對象,但File.read期待一個String對象,而不是(可能路徑的文件名)。

我不確定你想要做什麼,但是這個:file = File.read(response)是錯誤的。你不能這樣做,這就是爲什麼你會得到上述錯誤。

如果你真的想使用的文件,那麼你可以寫response到一個文件,然後讀取response從文件備份和使用:

f = File.new('response.txt', 'w+') # creating a file in read/write mode 
f.write(response) # writing the response into that file 
file_content = File.read('response.txt') # reading the response back from the file 

所以,問題不在於訪問Ruby中的第三方API JSON對象,但您嘗試以錯誤的方式使用File.read

你可以通過這樣瞭解從API的response

client = Kickbox::Client.new('YOUR_API_KEY') 
kickbox = client.kickbox() 
response = kickbox.verify("[email protected]") 

然後,您可以用response例如玩可以執行puts response.inspectputs response.body.inspect並查看該對象內部的內容。 並從那裏你只能提取你所需的輸出。

+0

非常感謝您的幫助!我試圖訪問響應中的「結果」對象 – Wilson