2012-11-05 33 views
1

我有一些Ruby代碼被撲滅JSON是這樣的:JSON渲染:如何包含左括號描述?

def nearby 
    #@bathrooms = Bathroom.geo_scope(:origin =>[params[:lat],[params[:lon]]], :within => 5) 
    lat = params[:lat] 
    lon = params[:lon] 
    #@bathrooms = Bathroom.geo_scope(:within => 5, :origin => [45.580639,-122.677682], :order=>'distance') 
    @bathrooms = Bathroom.geo_scope(:within => 3, :origin => [lat,lon], :order=>'distance') 
    respond_to do |format| 
    format.json { render :json => @bathrooms } 
    format.js { render :nothing => true } 
    end 
end 

的結果是這樣的:

[{"ID":129,"access":"1","avail":"0","bathroomtype":"0","city":"PORTLAND","comment":"","country":"US","created":"0000-00-00 00:00:00","directions":"The two bathrooms are in the long hallway at the back of the restaurant, past the bar.","distance":"2.94986114636676","lat":"45.539217","lon":"-122.661795","modifed":"0000-00-00","name":"Echo","postal":"97212-3727","slug":"echo-portland170","source":"","state":"OR","street":"2225 NE Martin Luther King Jr. Blvd"}, 

什麼我不知道該怎麼做的是命名集?例如,在第一個封閉支架後,我想命名浴室。我怎樣才能做到這一點是Rails?

回答

0

它看起來像@bathrooms是一個列表,所以你不能指定鍵在列表中的元素。你需要先製作一張地圖。例如,如果你只想要第一個元素:

format.json { render :json => {:bathrooms => @bathrooms[0]} } 

要設置所有的列表元素:

format.json { render :json => {:bathrooms => @bathrooms} } 
+0

由於方括號現在將這個集合命名爲浴室,這看起來更好。但是,我是否需要指定列表中的所有元素?這不僅僅是第一個記錄? –

+0

查看更新的答案。 –

+0

謝謝你做到了! –

1

嘗試:

render json: { bathrooms: @bathrooms } 
+0

都能跟得上,不做到這一點:我想: 渲染JSON:{浴室:@bathrooms } –

+0

這看起來不像有效的ruby語法。以我的答案爲例。 –

+0

這是一個完美的Ruby 1.9.2語法...如果您喜歡,請使用舊的hashrockets – apneadiving