Ruby on rails JSON&;Rails:如何删除JSON结果的keypath中的数组括号
我有一个JSON格式的问题——本质上,我只是试图删除从Rails控制器返回的keypath内对象周围的数组[]:Ruby on rails JSON&;Rails:如何删除JSON结果的keypath中的数组括号,ruby-on-rails,ruby-on-rails-3,json,Ruby On Rails,Ruby On Rails 3,Json,我有一个JSON格式的问题——本质上,我只是试图删除从Rails控制器返回的keypath内对象周围的数组[]: # channels controller def index @channels = Channel.all respond_to do |format| format.html # index.html.erb format.json { render :json => { :channels => @channels }
# 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}}}
这是不可能的。在JSON(只是JavaScript)中,对象列表不能不是数组或数组类型结构
如果您编辑您的问题,告诉我们您为什么要尝试实现这一点,我们可能会提供更多帮助。那么它将不再是一个有效的JSON。