Using JBuilder to create nested JSON output in rails

心已入冬 提交于 2019-12-17 19:46:54

问题


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

回答1:


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 


来源:https://stackoverflow.com/questions/14084117/using-jbuilder-to-create-nested-json-output-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!