URL的Ruby on Rails和JSON解析器 [英] Ruby on Rails and JSON parser from URL
问题描述
我使用'gem json',并且需要从某些 url 中加载JSON数据,例如:
I use 'gem json' and need load JSON data from some url, for example:
"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))
In string: @data = JSON.parse(JSON.load(source))
怎么了?如何获取和解析JSON数据?我尝试@data ["one"] ...
What is the matter? How can I get JSON data and parse it? I try @data["one"] ...
推荐答案
JSON.load
根据文档
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进行解析,就像这样...
You're giving it a String that is a URL and that's why you're getting an error. You can use open-uri
to fetch the data from the URL to then be parsed by JSON like so...
[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将数据转换为要使用的哈希.
open
returns a StringIO
object which responds to read
returning the JSON data. JSON.load turns the data into a hash to be used.
要解析JSON字符串,您可以使用JSON.load
或JSON.parse
To parse the JSON string you can either use JSON.load
or JSON.parse
这篇关于URL的Ruby on Rails和JSON解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!