我正在尋找一種方法將標識符添加到我的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
我想它有位置的名稱,以便我可以更輕鬆地解析它。謝謝您的幫助!
你說的「添加位置的名稱」是什麼意思?你想添加額外的內容到你的JSON對象嗎?目標並不完全清楚。 – Eupatoria
我已編輯帖子以顯示理想的格式 –
您只需修改您的JSON對象,使其具有「位置」的關鍵字並且值將成爲其餘部分。 – Eupatoria