0

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?

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.