我正在寻找一种方法来为我的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
我希望它有一个Locations的名称,这样我就可以更轻松地解析它。谢谢你的帮助!
答案 0 :(得分:2)
def index
@locations = Location.all
respond_with locations: @locations
end
输出正确的结果
答案 1 :(得分:0)
只需使用@locations
。
您可以执行以下操作:
@new_locations = {}
@new_locations = {'locations' => @locations}