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"
}
}
]
}
First of all Jbuilder is a template for rendering json responses. Rails comes preloaded with jbuilder gem which helps to create JSON structures. Lets see its use-case scenerio: For example we are making a blog app in which we have a lot of articles and users who create those articles. So we have two models a User model and an Article model.
This is probably the simplest way to build JSON APIs, all you have to do here is to use respond_to block in the controller action and render the appropriate model.
All these make Jbuilder a very good alternative to some of the traditional methods especially if the JSON representation in your APIs are complex. i.e, it involves a high degree of customization, it has a lot conditionals or nesting.
You can have Jbuilder in your applications through its gem. Just to demonstrate how Jbuilder helps solve the problems discussed so far: In the articles controller you can remove the respond_to call and revert to the default behavior which is to look for a template of the requested format.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With