2011-12-20 4 views
1

로 변환 JSON 및 분할 개체를 구문 분석 I이 다음 코드 : 모두의루비/레일 - 날짜

{"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 출력

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을 통해 심지어 루프 :

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

내가 다음에 split을 이용하고자 할 수 있습니다 :

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 

이 다음과 같은 오류를 제공합니다 "title" 그래서 시간과 날짜를 나중에 사용할 DateTime 개체로 변환 할 수 있습니다.

미리 감사드립니다.

+0

'NoMethodError : 정의되지 않은 메소드'each 'for nil : NilClass' 오류가 JSON에 대해 더 이해가됩니다. 오류 메시지가 코드와 JSON에서 온 것입니까? –

+1

원본 소스가 xml에 있기 때문에 Nokogiri를 사용하여 구문 분석을 수행하고 내용의 시간과 시간을 변환하는 대신 다른 방법을 사용합니다. –

+0

@muistooshort 예, 특정 코드 행과 JSON에서 오는 것입니다. – fuzz

답변

0

저는 XML을 JSON으로 변환하는 대신 XML을 구문 분석하기 위해 Nokogiri를 사용하기로 결정했습니다.

도움 주셔서 감사합니다.