2017-09-04 8 views
0

私はここに示すようにハッシュの配列を持っています。いくつかのフィールドの値をカスタムsepratorsにマージしたい。ここでは、配列に2つのハッシュしか表示されていないので、それ以上の配列を持つことは可能です。しかし、彼らは常にここに示されているように同じ順序です。同じキーでハッシュの配列をマージする

{ 
"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 
関連する問題