0

I'm writing an API parser at the moment, and I'm working on formatting the data nicely.

So far, I have the following code:

data.each {|season| episodes[season["no"].to_i] = season["episode"].group_by{|i| i["seasonnum"].to_i}}

However, the only issue with this is that the output comes out like this:

8 => {
     1 => [
        [0] {
                "epnum" => "150",
            "seasonnum" => "01",
              "prodnum" => "3X7802",
              "airdate" => "2012-10-03",
                 "link" => "http://www.tvrage.com/Supernatural/episodes/1065195189",
                "title" => "We Need to Talk About Kevin"
        }
    ],
     2 => [
        [0] {
                "epnum" => "151",
            "seasonnum" => "02",
              "prodnum" => "3X7803",
              "airdate" => "2012-10-10",
                 "link" => "http://www.tvrage.com/Supernatural/episodes/1065217045",
                "title" => "What's Up, Tiger Mommy?"
        }
    ]
}

So there's a redundant array in each value of the secondary hash. How would I remove this array and just have the inside hash? So, for example I want:

8 => {
     1 => {
                "epnum" => "150",
            "seasonnum" => "01",
              "prodnum" => "3X7802",
              "airdate" => "2012-10-03",
                 "link" => "http://www.tvrage.com/Supernatural/episodes/1065195189",
                "title" => "We Need to Talk About Kevin"
        }
    ,

etc.

EDIT: Here's the full file:

require 'httparty'
require 'awesome_print'
require 'debugger'
require 'active_support'

episodes = Hash.new{ [] }
response = HTTParty.get('http://services.tvrage.com/feeds/episode_list.php?sid=5410')
data = response.parsed_response['Show']['Episodelist']["Season"]

data.each { |season|
  episodes[season["no"].to_i] = season["episode"].group_by{ |i|
    i["seasonnum"].to_i
  }
}

ap episodes

Input data: http://services.tvrage.com/feeds/episode_list.php?sid=5410

chintanparikh
  • 1,632
  • 6
  • 22
  • 36
  • You should show an example of your input data, before you massage it. Also, reduce the size of the output. We don't need much to diagnose a problem, especially when the problem occurs repeatedly. – the Tin Man Feb 07 '13 at 21:24

2 Answers2

0

Wild guess:

data.each { |season|
  episodes[season["no"].to_i] = season["episode"].group_by{ |i|
    i["seasonnum"].to_i
  }.first
}
Jason Swett
  • 43,526
  • 67
  • 220
  • 351
0

It looks like you're using group_by (array of entries with same key) when you really want index_by (one entry per key).

data.each {|season| episodes[season["no"].to_i] = season["episode"].index_by {|i| i["seasonnum"].to_i}}

NOTE: If you can have MORE than one episode with the same seasonnum, you SHOULD use group by and have an array of values here. If you're just building a hash of episodes with a convenient lookup (one to one mapping), then index_by is what you want.

Winfield
  • 18,985
  • 3
  • 52
  • 65