Mark
Mark

Reputation: 33

How to structure JSON code in Ruby

I have a newbie question.

The Ruby code below returns JSON shown in Output1. How do I modify this to return the JSON shown in Output2 i.e., each record is within customer record.

Code:

def index
    @customers = Customer.all
    respond_to do |format|
        format.html
        format.json {render json: @customers.to_json}
    end
end

Output1:

[
    {
        "address":"123 Main Ave, Palo Alto, CA",
        "created_at":"2012-07-10T19:49:24Z",
        "id":1,
        "name":"ACME Software Inc.",
        "phone":"1-650-555-1500",
        "updated_at":"2012-07-10T19:49:24Z"
    },
    {
        "address":"555 Art Drive, Mountain View, CA",
        "created_at":"2012-07-10T19:50:19Z",
        "id":2,
        "name":"My Company",
        "phone":"1-415-555-1000",
        "updated_at":"2012-07-10T19:50:19Z"
    }
]

Output2:

[
    {
        "customer":{
            "address":"123 Main Ave, Palo Alto, CA",
            "created_at":"2012-07-10T19:49:24Z",
            "id":1,
            "name":"ACME Software Inc.",
            "phone":"1-650-555-1500",
            "updated_at":"2012-07-10T19:49:24Z"
        }
    },
    {
        "customer":{
            "address":"555 Art Drive, Mountain View, CA",
            "created_at":"2012-07-10T19:50:19Z",
            "id":2,
            "name":"My Company",
            "phone":"1-415-555-1000",
            "updated_at":"2012-07-10T19:50:19Z"
        }
    }
]

Upvotes: 3

Views: 164

Answers (3)

Anthony Alberto
Anthony Alberto

Reputation: 10395

Starting in Rails 3.2, you can do :

format.json {render json: @customers.to_json(:root => true)}

Upvotes: 3

x1a4
x1a4

Reputation: 19475

If you want this behavior for all models, you can do

ActiveRecord::Base.include_root_in_json = true

in an initializer.

For a single model, use

self.include_root_in_json = true

in the model itself.

Upvotes: 4

Trevoke
Trevoke

Reputation: 4117

Well, I have no idea WHY you want this, but here's one easy way:

format.json {render json: @customers.map{ |x| {'customer' => x } }.to_json}

Upvotes: 0

Related Questions