简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM