2015-11-18 21 views
0

我正在尋找一種方法將標識符添加到我的JSON輸出中,以便更輕鬆地進行解析。目前,輸出爲:在Ruby on Rails中添加JSON數組的標識符

[ 
    { 
     "id":9, 
     "name":"Test Location", 
     "description":"Test Description", 
     "address":"123 Fake Street", 
     "latitude":-85.0, 
     "longitude":-101.10101, 
     "created_at":"2015-11-15T21:25:08.643Z", 
     "updated_at":"2015-11-15T21:27:23.419Z" 
    }, 
    { 
     "id":10, 
     "name":"Test Location", 
     "description":"testest", 
     "address":"estesets", 
     "latitude":1.0, 
     "longitude":1.0, 
     "created_at":"2015-11-15T22:05:39.224Z", 
     "updated_at":"2015-11-15T22:05:39.224Z" 
    } 
] 

理想的輸出將是:

{ locations: 
    [ 
     { 
      "id":9, 
      "name":"Test Location", 
      "description":"Test Description", 
      "address":"123 Fake Street", 
      "latitude":-85.0, 
      "longitude":-101.10101, 
      "created_at":"2015-11-15T21:25:08.643Z", 
      "updated_at":"2015-11-15T21:27:23.419Z" 
     }, 
     { 
      "id":10, 
      "name":"Test Location", 
      "description":"testest", 
      "address":"estesets", 
      "latitude":1.0, 
      "longitude":1.0, 
      "created_at":"2015-11-15T22:05:39.224Z", 
      "updated_at":"2015-11-15T22:05:39.224Z" 
     } 
    ] 
} 

我現在的控制器是:

module Api 
    module V1 
    class LocationsController < ApplicationController 
unless Rails.env.test? 
     before_filter :restrict_access 
    end 
     respond_to :json 

     def index 
     @locations = Location.all 
     respond_with @locations 
     end 

     private 

     def restrict_access 
     api_key = ApiKey.find_by_access_token(params[:access_token]) 
     head :unauthorized unless api_key 
     end 
    end 
    end 
end 

我想它有位置的名稱,以便我可以更輕鬆地解析它。謝謝您的幫助!

+0

你說的「添加位置的名稱」是什麼意思?你想添加額外的內容到你的JSON對象嗎?目標並不完全清楚。 – Eupatoria

+0

我已編輯帖子以顯示理想的格式 –

+0

您只需修改您的JSON對象,使其具有「位置」的關鍵字並且值將成爲其餘部分。 – Eupatoria

回答

2
def index 
    @locations = Location.all 
    respond_with locations: @locations 
end 

結果在適當的輸出

+0

感謝您的迴應,但這會導致SyntaxError:語法錯誤,意外的':',期待'}'respond_with {locations:@locations}^ –

+0

它應該是response_with locations:@locations。大括號不是必需的 –

0

@locations只是工作。

你可以這樣做:

@new_locations = {} 
@new_locations = {'locations' => @locations}