Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
            }
        }
    ]
}
like image 747
ESoft Avatar asked Dec 29 '12 17:12

ESoft


People also ask

What is JBuilder in rails?

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.

What is the best way to build JSON APIs?

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.

Is JBuilder a good alternative to the traditional methods?

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.

How can I use JBuilder in my application?

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.


1 Answers

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 
like image 198
ESoft Avatar answered Oct 11 '22 12:10

ESoft