2012-04-26 37 views
0

我有一個JSON格式化問題 - 本質上我只是試圖從keypath中返回的keypath內的數組[ Rails控制器:JSON&Rails:如何刪除JSON結果keypath內的數組括號內容

# 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}}} 
+0

然後它不再是一個有效的JSON。 – 2012-04-26 22:58:08

回答

2

這是不可能的。您不能擁有JSON中不是數組或數組類型結構的對象列表(這僅僅是JavaScript)。

如果您編輯您的問題以告訴我們您爲什麼試圖達到此目的,我們可能會提供更多幫助。