简体   繁体   中英

JSON & Rails: How to remove array brackets inside keypath of JSON results

I've got a JSON formatting question -- essentially I'm just trying to remove the array [ ] around the objects inside the keypath that are returned from the Rails controller:

# channels controller
  def index
    @channels = Channel.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => { :channels => @channels } }
    end
  end

# channels.rb
  def as_json(options={})
    { self.id => self.attributes }
  end

# returns this JSON:
{"channels":[{"78":{"id":78,"name":"Zombie Bass","created_at":"2012-03-21T04:04:36Z","updated_at":"2012-04-20T01:21:12Z","num_of_listeners":1}},{"82":{"id":82,"name":"The Beatles123","created_at":"2012-03-22T20:28:34Z","updated_at":"2012-04-17T04:34:07Z","num_of_listeners":1}},{"125":{"id":125,"name":"New!","created_at":"2012-04-19T04:05:47Z","updated_at":"2012-04-19T04:05:47Z","num_of_listeners":1}},{"132":{"id":132,"name":"Test!","created_at":"2012-04-26T21:00:30Z","updated_at":"2012-04-26T21:00:30Z","num_of_listeners":1}}]}

# I want this JSON (just remove the array around all the channels):
{"channels":{"78":{"id":78,"name":"Zombie Bass","created_at":"2012-03-21T04:04:36Z","updated_at":"2012-04-20T01:21:12Z","num_of_listeners":1}},{"82":{"id":82,"name":"The Beatles123","created_at":"2012-03-22T20:28:34Z","updated_at":"2012-04-17T04:34:07Z","num_of_listeners":1}},{"125":{"id":125,"name":"New!","created_at":"2012-04-19T04:05:47Z","updated_at":"2012-04-19T04:05:47Z","num_of_listeners":1}},{"132":{"id":132,"name":"Test!","created_at":"2012-04-26T21:00:30Z","updated_at":"2012-04-26T21:00:30Z","num_of_listeners":1}}}

That isn't possible. You can't have a list of objects which isn't an array or array-type structure in JSON (which is just JavaScript).

If you edit your question to tell us why you are trying to achieve this, we may be able to help more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM