2014-04-27 78 views
0

我想從一個url在我的rails應用程序中獲取json數據。如何使這個API呼叫。Rails:從遠程URL/API調用獲取JSON數據

{ 
    "name": "MagicList", 
    "count": 20, 
    "frequency": "realtime", 
    "version": 5, 
    "newdata": true, 
    "lastrunstatus": "success", 
    "lastsuccess": "Sat Apr 26 2014 14:34:40 GMT+0000 (UTC)", 
    "results": { 
    "collection1": [ 
     { 
     "Title": { 
      "href": "http://www.magicbricks.com/propertyDetails/2-BHK-746-Sq-ft-Multistorey-Apartment-FOR-Sale-Sector-79-in-Gurgaon&id=C0gt4k2Fa9tzpSvf+uAgZw==", 
      "text": "2 BHK Multistorey Apartment in Sector-79" 
     }, 
     "Price": "37.99 Lac(s)", 
     "Rate": "5,092", 
     "Size": "746 Sq-ft", 
     "Project Name": "", 
     "New_Resale": "New Property" 
     }, 
     { 
     "Title": { 
      "href": "http://www.magicbricks.com/propertyDetails/2-BHK-1050-Sq-ft-Multistorey-Apartment-FOR-Sale-Sector-68-in-Gurgaon&id=M5jckQCuJaBzpSvf+uAgZw==", 
      "text": "2 BHK Multistorey Apartment in Sector-68" 
     }, 
     "Price": "57.50 Lac(s)", 
     "Rate": "5,476", 
     "Size": "1050 Sq-ft", 
     "Project Name": "Project: Pareena Sec68", 
     "New_Resale": "New Property" 
     }, 
     { 
     "Title": { 
      "href": "http://www.magicbricks.com/propertyDetails/3-BHK-1875-Sq-ft-Multistorey-Apartment-FOR-Sale-Sector-37C-in-Gurgaon&id=gw8zjmcA/b1zpSvf+uAgZw==", 
      "text": "3 BHK Multistorey Apartment in Sector-37C" 
     }, 
     "Price": "60.0 Lac(s)\nOnwards", 
     "Rate": "3,200", 
     "Size": "1875 Sq-ft", 
     "Project Name": "Project: Spire Greens", 
     "New_Resale": "Resale" 
     } 
    } 
    } 

不知道如何實現,應該使用哪種寶石。

回答

1

這不是你的問題的答案,但堆棧溢出不會讓我發佈沒有50聲望的評論。

您可能希望編輯您的問題的API密鑰,因爲它相當於使用其API服務的密碼。

+0

感謝James Duffy – Prem

3

使用 '開放-URI'

url = "http://..." 
data = JSON.parse(open(url).read) 

或者使用 'net' 的

require "net/http" 

url = "http://..." 
resp = Net::HTTP.get_response(URI.parse(url)) 
data = JSON.parse(resp.body) 
0

是的,你可以很容易地使用內置的東西:

uri = "https://yourapithinkg.com/list?api_key=#{ENV.fetch('API_KEY')}" 
result = JSON.parse(Net::HTTP.get(URI.parse(uri))) 

大多數人喜歡加載其他圖書館,但它並不值得。