19

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

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

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

我有 Rails 应用程序

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

4 回答 4

48

JSON.load根据文档获取一个String或对象的源IO

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

于 2013-09-02T23:04:50.343 回答
15

您可以使用如下 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)

或者 gem http 派对:

require 'httparty'

response = HTTParty.get('http://localhost:3000/qwerty/give_json.json')
json = JSON.parse(response.body)
于 2013-09-02T23:13:49.593 回答
3

默认情况下,已经在httparty.rbhttparty中包含了 JSON 库。 这意味着调用 to是不必要的。
require 'json'

感谢您提供这些示例!

于 2013-12-04T02:44:27.050 回答
2

您可以使用 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"]
于 2018-10-26T07:44:05.447 回答