Ruby on Rails和来自URL的JSON解析器

时间:2013-09-02 22:54:08

标签: ruby-on-rails ruby json parsing

我使用'gem json'并且需要从某些 url 加载JSON数据,例如:

"http://locallhost:3000/qwerty/give_json.json"

{"one":"Omg","two":125,"three":"Hu"}

我有rails app

class QwertyController < ApplicationController
    require 'json'

    def get_json
        source = "http://localhost:3000/qwerty/give_json.json"
        @data = JSON.parse(JSON.load(source))
    end
end

我收到错误

JSON::ParserError in QwertyController#get_json
795: unexpected token at 'http://localhost:3000/qwerty/give_json.json'

在字符串中:@data = JSON.parse(JSON.load(source))

怎么回事?如何获取JSON数据并解析它?我试试@data [“one”] ......

4 个答案:

答案 0 :(得分:45)

根据文档

JSON.load获取StringIO对象的来源

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON.html#method-i-load

[17] pry(main)> {hello: "World"}.to_json
=> "{\"hello\":\"World\"}"
[18] pry(main)> JSON.load(_)
=> {"hello"=>"World"}

你给它一个字符串就是一个URL,这就是你收到错误的原因。您可以使用open-uri从URL获取数据,然后由JSON解析,如此...

[22] pry(main)> require 'open-uri'
=> false
[23] pry(main)> JSON.load(open("https://api.github.com"))
=> {"current_user_url"=>"https://api.github.com/user",
 "authorizations_url"=>"https://api.github.com/authorizations",
 "emails_url"=>"https://api.github.com/user/emails",
 "emojis_url"=>"https://api.github.com/emojis",
 "events_url"=>"https://api.github.com/events",
 "feeds_url"=>"https://api.github.com/feeds",
 "following_url"=>"https://api.github.com/user/following{/target}",
 "gists_url"=>"https://api.github.com/gists{/gist_id}",
 "hub_url"=>"https://api.github.com/hub"}

注意

open返回一个StringIO对象,该对象响应read返回JSON数据。 JSON.load将数据转换为要使用的哈希。

要解析JSON字符串,您可以使用JSON.loadJSON.parse

答案 1 :(得分:13)

您可以使用如下所示的net / http库:

   require 'net/http'
   source = 'http://localhost:3000/qwerty/give_json.json'
   resp = Net::HTTP.get_response(URI.parse(source))
   data = resp.body
   result = JSON.parse(data)

或者宝石http派对:

require 'httparty'

response = HTTParty.get('http://localhost:3000/qwerty/give_json.json')
json = JSON.parse(response.body)

答案 2 :(得分:3)

默认情况下,httparty已在 httparty.rb 中包含JSON库。
这意味着无需调用require 'json'

感谢您提供这些示例!

答案 3 :(得分:1)

您可以使用JSON和net / http lib ..,如下:

require 'net/http'
require 'json'

url = "https://api.url/"
uri = URI(url)
response = Net::HTTP.get(uri)
data = JSON.parse(response)
objs.each do |data|
  title = data["title"]