我正在尝试让我的一个页面请求并显示来自last.fm API的信息。此时没有用户输入,我只希望我的应用程序上的根页面显示此API调用的结果。
我的last_fm控制器:
class LastFmController < ApplicationController
include HTTParty
format :json
base_uri 'http://ws.audioscrobbler.com/2.0/'
def self.get_events
return get('http://ws.audioscrobbler.com/2.0/', :query => {
:method => 'geo.getEvents',
:api_key => 'xxxxxyyyyyyzzzzz'})
end
def index
@events = LastFmController.get_events
end
end
我的last_fm #index视图为空,除了:<%= @events %>
。
当我转到last_fm #index视图时我得到的错误:
795: unexpected token at '<?xml version="1.0" encoding="utf-8"?>
<lfm status="ok">
<events xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" location="San Francisco, United States" page="1" perPage="10" totalPages="37" total="364" festivalsonly="0" tag="">
<event xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" >
<id>3782989</id>
<title>Broken Hope</title>
<artists>
<artist>Broken Hope</artist>
<artist>Oceano</artist>
这条跟踪实际上包含了我从API调用中收到的整个哈希值,所以它很长,我为了简洁起见省略了它。
错误页面的标题是Action Controller: Exception caught
。
如果我可以使用我收到的哈希进行一些基本操作,比如能够导航哈希并仅显示某些项目,我将感激不尽。谢谢!
答案 0 :(得分:4)
您正在尝试将XML解析为JSON。这里的XML解析器:Nokogiri
答案 1 :(得分:2)
LastFM默认返回XML。您必须将 format = json 作为参数传递,以便返回JSON。这应该有效:
class LastFmController < ApplicationController
include HTTParty
format :json
base_uri 'http://ws.audioscrobbler.com/2.0/'
def self.get_events
return get('http://ws.audioscrobbler.com/2.0/', :query => {
:method => 'geo.getEvents',
:format => 'json',
:api_key => 'xxxxyyyyyzzzz'})
end
def index
@events = LastFmController.get_events
end
end