Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
        }
    }
]
like image 483
Mark Avatar asked Apr 14 '26 18:04

Mark


1 Answers

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.

like image 193
x1a4 Avatar answered Apr 17 '26 09:04

x1a4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!