2014-03-12 41 views
0

我想從一個散列解碼JSON,我找不到一個方法來做到這一點。我已使用此代碼:JSON從一個URL到一個散列

@summoner = 'https://prod.api.pvp.net/api/lol/na/v1.3/summoner/by-name/TurtleTown?api_key=xxxxxxxxxxxxx' 
@summoner = ActiveSupport::JSON.decode(@summoner) 

@summoner是一個包含JSON的網址。我如何獲得JSON形式的網址?

+0

代碼示例,請 – rpax

+0

召喚=「https://prod.api.pvp.net/api/lol/na/v1.3/summoner/by-name/TurtleTown ?api_key = XXXXXXXXXXXX' summoner = ActiveSupport :: JSON.decode(summoner) – linogomez

+0

什麼?在答案中發佈它,請 – rpax

回答

0

你在@summoner變量中有一個字符串,你需要使用某些東西來實際發出請求(除非你省略了那段代碼)。像Net::HTTP

1

一些requred庫是:

require 'net/http' 
require 'json' 

您將需要安裝json寶石。欲瞭解更多信息,請看here

首先執行獲取請求給定的網址。然後解碼請求響應:

#convert your link to URI object understandable by Net:HTTP library 
uri = URI('https://prod.api.pvp.net/api/lol/na/v1.3/summoner/by-name/TurtleTown?api_key=xxxxxxxxxxxxx') 

#perform actual GET request to given uri 
response = Net::HTTP.get_response(uri) 

#convert JSON response into hash if request was successful 
data = JSON.parse(response) if response.is_a?(Net::HTTPSuccess) 
+0

我得到(未定義的方法'主機名') – linogomez

+0

嘗試編輯的代碼。我不小心使用了uri字符串中的換行符。 –

+0

現在我得到(達到文件結束)安裝json後 – linogomez

相關問題