2017-09-04 57 views
0

我有一个散列数组,如下所示。我想合并一些字段的值与自定义分隔符。在这里,我只显示了数组中的两个哈希值,可以有更多。但是,它们总是以相同的顺序显示在这里。用相同的密钥合并散列数组

{ 
"details": [ 
{ 
    "place": "abc", 
    "group": 3, 
    "year": 2006, 
    "id": 1304, 
    "street": "xyz 14", 
    "lf_number": "0118", 
    "code": 4433, 
    "name": "abc coorperation", 
    "group2": 3817, 
    "group1": 32, 
    "postal_code": "22926", 
    "status": 2 
}, 
{ 
    "place": "cbc", 
    "group": 2, 
    "year": 2007, 
    "id": 4983, 
    "street": "mnc 14", 
    "lf_number": "0145", 
    "code": 4433, 
    "name": "abc coorperation", 
    "group2": 3817, 
    "group1": 32, 
    "postalcode": "22926", 
    "status": 2 
} 
], 
"@timestamp": "2017-09-04", 
"parent": { 
    "child": [ 
    { 
    "w_2": 0.5, 
    "w_1": 0.1, 
    "id": 14226, 
    "name": "air" 
    }, 
    { 
    "w_2": null, 
    "w_1": 91, 
    "id": 25002, 
    "name": "Water" 
    }] 
}, 
"p_name": "anacin", 
"@version": "1", 
"id": 28841 
} 

我想编辑的细节。我想要构建新的领域。

Field 1) coorperations: (details.name | details.postal_code details.street ; details.name | details.postal_code details.street) 

Output: 
Coorperations: (abc coorperation |22926 xyz 14; abc coorperation | 22926 mnc 14) 

Field 2) access_code: (details.status-details.id-details.group1-details.group2-details.group(always two digit)/details.year(only last two digits); details.status-details.id-details.group1-details.group2-details.group(always two digit)/details.year(only last two digits)) 

Output: access_code (2-32-3817-03-06; 2-32-3817-02-07) 

我怎样才能在细节实现这一目标的所有值。最终的结果应该如何。

{ 
"@timestamp": "2017-09-04", 
"parent": { 
"child": [ 
{ 
    "w_2": 0.5, 
    "w_1": 0.1, 
    "id": 14226, 
    "name": "air" 
    }, 
    { 
    "w_2": null, 
    "w_1": 91, 
    "id": 25002, 
    "name": "Water" 
    }] 
}, 
"p_name": "anacin", 
"@version": "1", 
"id": 28841, 
"Coorperations" : "abc coorperation |22926 xyz 14; abc coorperation | 22926 mnc 14", 
"access_code" : "2-32-3817-03-06; 2-32-3817-02-07" 
} 

回答

0

你可以尝试运行与哈希轨控制台这个代码是你的JSON:

new_hash = hash.except(:details) 
coorperations = "" 
access_code = "" 
elements = hash[:details] 
elements.each do |element| 
    coorperations = "#{coorperations}#{if coorperations.present? then '; ' else '' end}#{element[:name]} | #{element[:postal_code]} #{element[:street]}" 
    access_code = "#{access_code}#{if access_code.present? then '; ' else '' end}#{element[:status]}-#{element[:id]}-#{element[:group1]}-#{element[:group2]}-#{element[:group1]}-#{element[:group]}" 
end 
new_hash.merge!(Coorperations: coorperations) 
new_hash.merge!(access_code: access_code) 
new_hash