简体   繁体   中英

Using JBuilder to create nested JSON output in rails

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"
            }
        }
    ]
}

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 

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