无法在Rails中解析JSON [英] Failing to parse JSON in Rails

查看:177
本文介绍了无法在Rails中解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的页面之一请求并显示来自last.fm API的信息.此时,没有用户输入,我只希望应用程序上的根页面显示此API调用的结果.

I am trying to have one of my pages request and display info from the last.fm API. At this point there is no user input and I just want the root page on my application to display the results of this API call.

我的last_fm控制器:

My last_fm Controller:

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 %>.

My last_fm#index view is empty except this: <%= @events %>.

我进入last_fm#index视图时遇到的错误:

The error I'm getting when I go to the last_fm#index view:

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调用中收到的整个哈希,因此它很长,为简洁起见,我将其省略.

This trace actually includes the entire hash I received from the API call, so it's long and I'm omitting it for brevity.

错误页面的标题为Action Controller: Exception caught.

如果能对接收到的哈希进行一些基本操作,例如能够导航哈希并仅显示某些项目,我将不胜感激.谢谢!

I would be thankful if I could just do some basic manipulation with the hash I received, like being able to navigate the hash and only display certain items. Thanks!

推荐答案

LastFM默认返回XML.您必须将 format = json 作为参数传递,以便它返回JSON.这应该起作用:

LastFM returns XML by default. You have to pass in format=json as a paramter so it returns JSON. This should work:

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

这篇关于无法在Rails中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆