使用Ruby on Rails从另一个Web服务获取和解析JSON

时间:2021-07-23 16:47:13

I'm using Ruby on Rails to connect to various external web services, including Flickr, to receive some JSON data. I'd like to request this data and ideally, get it parsed into a arrays and hashes.

我正在使用Ruby on Rails连接到各种外部Web服务,包括Flickr,以接收一些JSON数据。我想请求这些数据,理想情况下,将其解析为数组和哈希值。

How does one get JSON data over HTTP and turn it into arrays and hashes using Ruby on Rails? Thanks.

如何通过HTTP获取JSON数据并使用Ruby on Rails将其转换为数组和哈希?谢谢。

2 个解决方案

#1


35  

Try something like this

尝试这样的事情

require 'open-uri'
require 'json'

result = JSON.parse(open("url_of_json_service").read)

See more abut the JSON gem here: http://flori.github.com/json/

在这里查看更多JSON gem:http://flori.github.com/json/

#2


1  

I've never had to do this so these are just some ideas to look into...

我从来没有这样做,所以这些只是一些想法来研究......

If you're doing this from client side you could probably just make a JSONP request and manipulate the JSON object however you want.

如果您是从客户端执行此操作,则可能只是发出JSONP请求并根据需要操作JSON对象。

Otherwise, if you want to make these calls from your server, you'd probably want to look into the Ruby Net HTTP library.

否则,如果您想从服务器进行这些调用,您可能需要查看Ruby Net HTTP库。

Then to serialize and deserialize JSON you can use this gem. It's the first one I found. There are probably others.

然后,为了序列化和反序列化JSON,您可以使用此gem。这是我发现的第一个。可能还有其他人。

#1


35  

Try something like this

尝试这样的事情

require 'open-uri'
require 'json'

result = JSON.parse(open("url_of_json_service").read)

See more abut the JSON gem here: http://flori.github.com/json/

在这里查看更多JSON gem:http://flori.github.com/json/

#2


1  

I've never had to do this so these are just some ideas to look into...

我从来没有这样做,所以这些只是一些想法来研究......

If you're doing this from client side you could probably just make a JSONP request and manipulate the JSON object however you want.

如果您是从客户端执行此操作,则可能只是发出JSONP请求并根据需要操作JSON对象。

Otherwise, if you want to make these calls from your server, you'd probably want to look into the Ruby Net HTTP library.

否则,如果您想从服务器进行这些调用,您可能需要查看Ruby Net HTTP库。

Then to serialize and deserialize JSON you can use this gem. It's the first one I found. There are probably others.

然后,为了序列化和反序列化JSON,您可以使用此gem。这是我发现的第一个。可能还有其他人。