【问题标题】:Rails: Fetch JSON Data from Remote URL / API CallRails:从远程 URL / API 调用中获取 JSON 数据
【发布时间】:2014-06-12 17:18:57
【问题描述】:

我正在尝试从 url 获取我的 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"
      }
     }
   }

不知道如何实现,应该使用哪个gem。

【问题讨论】:

    标签: ruby-on-rails ruby json api


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      使用'open-uri'

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

      或使用“网络”

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

      【讨论】:

        【解决方案3】:

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

        您可能想编辑您的 API 密钥,因为它相当于您使用他们的 API 服务的密码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多