【发布时间】:2015-07-26 17:39:15
【问题描述】:
我目前正在获取两个 JSON 数组,并将它们存储在名为 json_one 和 json_two 的变量中。一切正常,但现在我想以某种方式将它们组合成一个数组。
如何将 2 个数组与一个字典结合起来?
json_one
[
{
"address": "1031 25th Street San Diego, CA 92102",
"id": 1,
"resource_type_id": 3,
}
]
json_two
[
{
"resource_id": 4,
}
[
我试过这个......
def show
@user = User.find(params[:user_id])
@favorite = @user.favorites.find(params[:id])
@resource_data = []
(@resource_data << @favorite.resource_type.community_resources.where(:id => @favorite.resource_id)).flatten!
(@resource_data << @favorite.resource_type.district_resources.where(:id => @favorite.resource_id)).flatten!
(@resource_data << @favorite.resource_type.military_resources.where(:id => @favorite.resource_id)).flatten!
(@resource_data << @favorite.resource_type.school_resources.where(:id => @favorite.resource_id)).flatten!
@favorite_data = []
(@favorite_data << @favorite)
json_one = @resource_data.to_json(:only => [:id, :resource_type_id,:district_id,
:school_id, :name, :description, :website, :phone, :email, :address, :latitude, :longtude])
json_two = @favorite_data.to_json(:only => [:resource_id])
array1 = JSON.parse(json_one)
array2 = JSON.parse(json_two)
#array1 << array2
#firsts = array2.map {|array2| array2.first}
combined = [ array1.first.merge(array2.first) ]
respond_to do |format|
format.html
format.json { render json: data }
end
end
###but this is my result.
###I would like both dictionaries to be combined into one.
[
{
"address": "1031 25th Street San Diego, CA 92102",
"id": 1,
"resource_type_id": 3,
}
{
"resource_id": 4,
}
]
【问题讨论】:
标签: ruby-on-rails arrays ruby json dictionary