2013-02-07 79 views
0

我正在编写一个API解析器,而且我正在很好地格式化数据。如何从一个散列数组中提取散列?

到目前为止,我有以下代码:

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

然而,这唯一的问题是输出出来是这样的:

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?" 
     } 
    ] 
} 

所以这是每个冗余阵列次散列的值。我将如何删除这个数组,并只有内部散列?所以,例如我想:

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" 
     } 
    , 

编辑:下面是完整的文件:

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 

输入数据:http://services.tvrage.com/feeds/episode_list.php?sid=5410

+0

您应该在按摩之前显示输入数据的示例。另外,减小输出的大小。我们不需要太多来诊断问题,特别是当问题重复出现时。 –

+0

@TheTinMan完成:) – chintanparikh

回答

0

大胆猜测:

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

它看起来像你正在使用group_by(具有相同键的条目数组)时,如果你真的想要index_by(每个键一个条目)。

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

注意:如果你的节目数量可能超过一集,那么你应该使用group by,并在这里使用数组值。如果您只是通过方便的查找(一对一映射)来构建剧集的散列,那么index_by就是您想要的。

+0

我得到未定义的方法index_by? – chintanparikh

+0

这包含在active_support中,它扩展了ruby标准枚举类型:http://api.rubyonrails.org/classes/Enumerable.html – Winfield

+0

奇怪的是,它肯定会说未定义的方法。数组是可枚举的吗?编辑:其实是的,他们必须是因为group_by工作 – chintanparikh

相关问题