13

I have an array of JSON in my Rails App in this format using Active Model Serializer:

[
  {
    "contact" : {}
  },
  {
    "contact" : {}
  }
]

How do I make it so that I remove one level of node above the contact USING active model serializer like this:

[
 {
 },
 {
 }
]

I also want to remove the node name "contact".

peterh
  • 11,875
  • 18
  • 85
  • 108
Madhan
  • 498
  • 1
  • 6
  • 19

4 Answers4

25

This was covered in RailsCast #409 Active Model Serializers.

In order to remove the root node, you add root: false in the call to render in your controller. Assuming your contacts in JSON come from a contacts#index method, your code may look something like:

def index
  @contacts = Contacts.all
  respond_to do |format|
    format.html
    format.json { render json: @contacts, root: false }
  end
end

Or, if you don't want any root nodes in any of your JSON, in your ApplicationController, add the following method:

def default_serializer_options
  {root: false}
end
Paul Fioravanti
  • 16,423
  • 7
  • 71
  • 122
  • I actually do have that setup. I guess I didn't explain it correctly. The object has a list of attributes including the contact object and I have hidden all the other attributes. I just want the contact object to be the root. – Madhan Mar 12 '13 at 16:17
15

For people using ActiveModel::Serializer v0.10.x, you will need to create an initializer and include the following:

# config/initializers/serializer.rb
ActiveModelSerializers.config.adapter = :json
ActiveModelSerializers.config.json_include_toplevel_object = true

Then, just restart your app and you should get the root objects you desire.

This works in Rails 5.1.x. YMMV. HTH.

Dan Laffan
  • 1,544
  • 12
  • 12
6

/config/initializers/serializer.rb

ActiveModelSerializers.config.adapter = :json_api # Default: `:attributes`

By default ActiveModelSerializers will use the Attributes Adapter (no JSON root). But we strongly advise you to use JsonApi Adapter, which follows 1.0 of the format specified in jsonapi.org/format.

Albert.Qing
  • 4,220
  • 4
  • 37
  • 49
5

Usually the root node has the name of your controller by default if I am not wrong.

format.json { render json: @contacts}

Of course you need to remove root false, it removes the node's name.

If you want contact as root object use this:

format.json { render json :@contacts, :root => 'contact' }
Freddo
  • 523
  • 6
  • 16
rbinsztock
  • 3,025
  • 2
  • 21
  • 34