pandaman pandaman - 6 months ago 41
JSON Question

How to iterate through a nested array in a JSON object (Rails)

How can I iterate over an array nested as a value inside a JSON object? This will be rendered in a

.html.erb
file.

This results in displaying the actual array in the view.

<% @data.each do |y| %>
<%= y["name"] %>
<%= y["location"] %>

<%= y["cars"] %>

<%= y["married"] %>
<% end %>


This results in an
undefined method 'each' for nil:NilClass
.

<% @data.each do |y| %>
<%= y["name"] %>
<%= y["location"] %>

<% y["cars"].each do |z| %>
<%= z["make"] %>
<%= z["value"] %>
<% end %>

<%= y["married"] %>
<% end %>


JSON

[
{
"name":"Jim",
"location":"London",
"cars": [
{
"make":"Audi",
"value":"100k"
}
],
"married": "Y"
},
{
"name":"Sarah",
"location":"New York",
"cars": [
{
"make":"Ferrari",
"value":"200k"
},
{
"make":"Lambo",
"value":"350k"
}
],
"married": "Y"
},
]


Has anyone successfully implemented this with JSON in a Rails template before?

Answer

Have you parsed JSON before in controller/service with JSON.parse? I asked because that is strange case when you have empty y["cars"] in array... in some cases...

If yes stub nil value for :cars in if it is empty with an empty array []:

<%- (y["cars"] || []).each do |z| %>
    <%= z["make"] %>
    <%= z["value"] %>
<%- end %>

and do better it with a decorator (see draper gem).