Rails:从远程URL/API调用中获取JSON数据 [英] Rails: Fetch JSON Data from Remote URL / API Call

查看:189
本文介绍了Rails:从远程URL/API调用中获取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从URL获取Rails应用程序中的json数据.如何进行此api调用.

i am trying to fetch a json data in my rails app from a url. how to make this api call.

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

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

dont know how it can be achieved, which gem should be used.

推荐答案

使用'open-uri'

Using '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)

这篇关于Rails:从远程URL/API调用中获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆