我目前正在获取两个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,
}
]
答案 0 :(得分:1)
json_one = "[{\"address\":\"1031 25th Street San Diego, CA 92102\",\"id\":1,\"resource_type_id\":3}]"
json_two = "[{\"resource_id\":4}]"
array1 = JSON.parse(json_one)
array2 = JSON.parse(json_two)
combined = [ array1.first.merge(array2.first) ]
respond_to do |format|
format.html
format.json { render json:combined }
end
FWIW,我会在没有JSON的情况下这样做:
combined = @resource_data.slice( :id, :resource_type_id,:district_id,
:school_id, :name, :description, :website,
:phone, :email, :address, :latitude, :longtude )
.merge( @favorite_data.slice( :resource_id ))
这会从@resource_data
中提取所需的属性,并将其与@favorite_data resource_id
属性合并。
请参阅Rails slice docs。