2011-12-20 52 views
1

我有以下代碼:的Ruby/Rails - 解析JSON和拆分對象轉換爲datetime

page = Net::HTTP.get_response(URI.parse('http://www.enhancetv.com.au/tvguide/rss/melbournerss.php')).body rescue nil 
show_info = Hash.from_xml(page).to_json 
puts show_info 

,它輸出以下JSON:我想

{"rss":{"version":"2.0","channel":{"title":"EnhanceTV Melbourne TV Guide ","description":null,"link":"http://www.enhancetv.com.au","lastBuildDate":"Wed, 21 Dec 
2011 10:25:55 1000","generator":"FeedCreator 1.7.2","item":[{"title":"Toasted TV - TEN - 07:00:00 - 21/12/2011","link":"http://www.enhancetv.com.au/tvguide/","d 
escription":"Join the team for the latest in gaming, sport, gadgets, pop culture, movies, music and other seriously fun stuff! Featuring a variety of your favou 
rite cartoons."},{"title":"Totally Wild - TEN - 08:00:00 - 21/12/2011","link":"http://www.enhancetv.com.au/tvguide/","description":"The Totally Wild team brings 
you the latest in action, adventure and wildlife from Australia and around theglobe."},{"title":"Explore: Africa's Rift Valley - SBS ONE - 19:30:00 - 21/ 
12/2011","link":"http://www.enhancetv.com.au/tvguide/","description":"Simon Reeve leads a team of journalists on a spectacular journey down East Africa's R 
ift Valley. From the tiny country of Djibouti, which is the centre of America's military presence in Africa, to the wide open plains of Kenya, the team enc 
ounter awe-inspiring landscapes, rich culture and amazing wildlife."}]}}} 

首先,實際上能夠遍歷每個項目。

這是我到目前爲止,但它是拋出一個錯誤。我不完全知道如何甚至通過解析JSON循環正常:

result = JSON.parse(show_info) # convert JSON data to native ruby 

result["channel"].each do |a| 
    puts a['title'] 
    puts a['description'] 
    puts a['link'] 
end 

這提供了以下錯誤:

scraper.rb:118:in `<main>': undefined method `each' for "rss":String (NoMethodEr 
ror) 

那麼我希望能夠做到在一個split"title",因此我可以將時間和日期轉換爲稍後使用的DateTime對象。

在此先感謝。

+0

對於那個JSON,'NoMethodError:未定義的方法'each'for nil:NilClass'對我來說更有意義。你確定那個錯誤信息來自代碼和那個JSON嗎? – 2011-12-21 00:07:29

+1

由於原始來源是在xml中使用Nokogiri做解析和其他任何其他內容,而不是轉換內容的時間和時間。 – 2011-12-21 00:07:38

+0

@ muistooshort對,它絕對來自特定的代碼行和JSON。 – fuzz 2011-12-21 00:09:33

回答

0

我決定使用Nokogiri來解析XML而不是將XML轉換爲JSON。

感謝您的幫助。