matski matski - 1 month ago 20
JSON Question

ruby nokogiri iterate over nested items

I have this html

<div class="date">
<h3 class="date-title">Today</h3>

<div class="film">
<img class="poster" src="film1" />
<h4 class="title">Film 1</h4>
<ul class="session-times">
<li>
<a href="#">
<time>12:00 PM</time>
</a>
</li>
</ul>
</div><!-- /.film -->

<div class="film">
<img class="poster" src="film2" />
<h4 class="title">Film 2</h4>
<ul class="session-times">
<li>
<a href="#">
<time>3:00 PM</time>
</a>
</li>
</ul>
</div><!-- /.film -->

<div class="film">
<img class="poster" src="film3" />
<h4 class="title">Film 3</h4>
<ul class="session-times">
<li>
<a href="#">
<time>6:00 PM</time>
</a>
</li>
</ul>
</div><!-- /.film -->
</div><!-- /.date -->

<div class="date">
<h3 class="date-title">Tomorrow</h3>

<div class="film">
<img class="poster" src="film1" />
<h4 class="title">Film 1</h4>
<ul class="session-times">
<li>
<a href="#">
<time>2:00 PM</time>
</a>
</li>
</ul>
</div><!-- /.film -->

<div class="film">
<img class="poster" src="film2" />
<h4 class="title">Film 2</h4>
<ul class="session-times">
<li>
<a href="#">
<time>5:00 PM</time>
</a>
</li>
</ul>
</div><!-- /.film -->

<div class="film">
<img class="poster" src="film3" />
<h4 class="title">Film 3</h4>
<ul class="session-times">
<li>
<a href="#">
<time>8:00 PM</time>
</a>
</li>
</ul>
</div><!-- /.film -->
</div><!-- /.date -->


and I'm extracting data using this Ruby code

nokogiri_object.css('.date').each do |d|
date = d.css('.date-title').text
dates.push(date: date)
d.css('.film').each do |film|
title = film.css('.title')
title_en = title.text.strip
time = film.css('.session-times/li/a/time').text
end
end


this gives me

[
{
"date": "Today"
},
{
"date": "Tomorrow"
}
]


but I'd like to loop over the 3 movies an times in each ".film" section and include them under each date in the output. So it should look more like this

[
{
"Today": {
"films": [
{
"film": "Film1",
"time": "12:00 PM"
},
{
"film": "Film2",
"time": "15:00 PM"
},
{
"film": "Film3",
"time": "6:00 PM"
}
]
},
{
"Tomorrow": {
"films": [
{
"film": "Film1",
"time": "14:00 PM"
},
{
"film": "Film2",
"time": "5:00 PM"
},
{
"film": "Film3",
"time": "8:00 PM"
}
]
},


I can't figure out where to build my array within the nested loop.

Thanks.

Answer
 nokogiri_object.css('.date').map { |date| { date.css('.date-title').text => { "films" => date.css('.film').map { |film| { "film" => film.css('img.poster').attr('src').value, "time" => film.css('time').text } } } } }
 => [{"Today"=>{"films"=>[{"film"=>"film1", "time"=>"12:00 PM"}, {"film"=>"film2", "time"=>"3:00 PM"}, {"film"=>"film3", "time"=>"6:00 PM"}]}}, {"Tomorrow"=>{"films"=>[{"film"=>"film1", "time"=>"2:00 PM"}, {"film"=>"film2", "time"=>"5:00 PM"}, {"film"=>"film3", "time"=>"8:00 PM"}]}}]