Rails:从远程URL / API调用获取JSON数据

时间:2014-04-27 04:33:48

标签: ruby-on-rails ruby json api

我正在尝试从网址中获取我的rails应用中的json数据。如何进行这个api通话。

 {
  "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"
      }
     }
   }

不知道如何实现,应该使用哪种宝石。

3 个答案:

答案 0 :(得分:3)

使用'open-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)

答案 1 :(得分:1)

这不是你问题的答案,但是堆栈溢出不会让我发表评论而没有50个声誉。

您可能希望修改自己的API密钥,因为它与您使用其API服务的密码相当。

答案 2 :(得分:0)

是的,你可以轻松使用内置的东西:

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

大多数人喜欢加载其他库,但它并不值得。