Using JBuilder to create nested JSON output in rails

ESoft picture ESoft · Dec 29, 2012 · Viewed 12k times · Source

I am looking for examples on how to create nested JSON output using JBuilder.

I want to create and output similar to this:

{
    "name": "John Doe", 
    "reservations": [
        {
            "restaurant": "ABC",
            "reservation_time": "2012/12/01 20:00", 
            "details": {
                "address": "somewhere", 
                "rating": "5"
            }
        }, 
        {
            "restaurant": "CDE",
            "reservation_time": "2012/12/04 20:00", 
            "details": {
                "address": "somewhere else", 
                "rating": "3"
            }
        }
    ]
}

Answer

ESoft picture ESoft · Dec 29, 2012

Solved:

json.name user.name

json.array!(@reservations) do |json, reservation|
    json.restaurant reservation.restaurant.name
    json.reservation_time reservation.time

    json.details do 
        json.address reservation.restaurant.address 
        json.rating reservation.restaurant.rating 
    end
end