input = {"color"=>["red"],"size"=>["s","l"]}
json_obj = [{"color":"red","id":"123","size":"s","name":"test"},
{"color":"yellow","id":"124","size":"s","name":"test"},
{"color":"red","id":"125","size":"l","name":"test"}]
输出应为
output["red_s"] = {"color":"red","id":"123","size":"s","name":"test"}
output["red_l"] = {"color":"red","id":"125","size":"l","name":"test"}
输出是json_obj上输入和查找的组合。 如何获得轨道输出?
我有以下脚本来获取组合ie.red_s和red_l,
ary = input.map {|k,v| [k].product v}
output = ary.shift.product(*ary).map {|a| Hash[a]}
和
output[red_s]=json_obj.find{|h| h["color"] == "red" and h["size"] == "S"}
我不想在上面的颜色和大小等代码中使用任何硬编码。
答案 0 :(得分:0)
我认为这应该让你接近你想要的。 注意你的json数组对象周围的“ticks”(你拥有的是无效的ruby) 另一个问题是你必须想出一个更好的方法来创建输出哈希键。
require 'json'
input = {"color"=>["red"],"size"=>["s","l"]}
output = {}
json_obj = '[{"color":"red","id":"123","size":"s","name":"test"},
{"color":"yellow","id":"124","size":"s","name":"test"},
{"color":"red","id":"125","size":"l","name":"test"}]'
found = JSON.parse json_obj
input.each_key do |key|
found = found.select { |item| input[key].include?(item[key]) }
end
puts found
found.each do |item|
output_key = ""
input.each_key do |key|
output_key = "#{item[key]}_" + output_key
end
output["#{output_key}"] = item.to_json
end
puts output