0

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.

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

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

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>

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

The title of the error page is 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!

2 Answers 2

4

You are trying to parse XML as JSON. XML parser here: Nokogiri

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

looking back at this question with a few years more experience, i cringe when i see i included my api key. not that i got hacked, but i wish you'd told me :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.