将三个哈希值合并到现有哈希值组合中

时间:2017-02-05 12:55:26

标签: ruby

我试图创建一个清单文件,其中包含所有微服务版本,代码和来自不同json文件的名称到现有文件中。请参阅下面现有的.json模板:

{
  "name": "MS Suite",
  "version": "2017.1.0"
}

我想解析其他json文件并将哈希和合并组合在一起,这应该是这样的:

{
 "name": "MS Suite",
 "version": "2017.1.0",
 "components": [
{
  "code": "1x.2017",
  "name": "microservice1",
  "version": "1.1.3-1"
},
{
  "code": "3x.2017",
  "name": "microservice2",
  "version": "1.1.15-1"
},
{
  "code": "2x.2017",
  "name": "microservice3",
  "version": "1.1.17-1
 }  ...
]
}

经过艰苦的研究后,我设法解析这些.json文件并设法从所有json文件中获取这个代码,名称,版本的大哈希,但是我遇到了很多问题: 1.不能反转哈希值,因为它是相同的键(代码/名称/版本),所以它只返回一行,所以现在我有#34;值":&# 34;键" 2.我正在从三个数组创建这个最终哈希,所以它将创建包含所有代码,所有名称和最终所有版本的数组 3.我还需要将其合并到上面粘贴的模板中。 现在我的功能看起来像这样:

code=[]
name=[]
version=[]
stream.each do |s|
file = File.read("./resources/release/release-updates/#{s}/manifest.json")
data_hash = JSON.parse(file)
data_hash['services'].each do |h|
  code << h['code']
  name << h['name']
  version << h['service-version']
  c = Hash[code.map {|v| [v, 'code']}]
  n = Hash[name.map {|v| [v, 'name']}]
  v = Hash[version.map {|v| [v, 'version']}]
  a  = [c, n, v]
  @result = a.inject(&:merge)#Hash[*a.map(&:to_a).flatten]
end
end
puts @result.to_json

所以你注意到用于解析的.json文件存储在这里:./ resources / release / release -updates /#{}} / manager.json,其中s = stream,它可以是核心&amp;处理和包装。如果您想要帮助,可以在此位置创建2或3个json文件,并尝试合并位于当前文件夹中的模板。我需要获取代码,名称和服务版本的这些2或3个文件都是这样的:

 ...
 "services": [{
    "name": "1 Micro service",
    "service-name": "microservice1",
    "code": "1x",
    "service-version": "3.1.3-1",
    "cookbook-name": "microservice1",
    "cookbook-version": "0.2.63",
    "cookbook-repo": "ssh://git..."
}, {
    "name": "2 Micro service",
    "service-name": "microservice2",
    "code": "1x",
    "service-version": "3.1.6-1",
    "cookbook-name": "microservice2",
    "cookbook-version": "0.1.73",
    "cookbook-repo": "ssh://git...."
}...

输出

{"1x":"code","2x":"code","3x":"code","4x":"code","5x":"code","6x":"code","microservice1":"name","microservice2":"name","microservice3":"name","microservice4":"name","microservice5":"name","microservice6":"name","3.1.3-1":"version","3.1.6-1":"version","3.1.9-1":"version","2017.1.0.0-17_1":"version","2017.1.0.47-RELEASE":"version","1.8.3-1":"version"}

1 个答案:

答案 0 :(得分:1)

所以基本上我们需要从模板创建一个哈希,并从.json文件的值中创建另一个哈希

components = []
stream.each do |s|
file = File.read("path.../#{s}/manifest.json")
data_hash = JSON.parse(file)
components << data_hash['services'].map do |h|
   {
    'code' => h['code'],
    'name' => h['name'],
    'version' => h['service-version']
   }
end
end

模板中的哈希

mainfestfile = File.read("path...")
header = JSON.parse(mainfestfile)

和合并

concatenated = components.flatten
header['components'] = concatenated
puts header.to_json

或保存:

 File.open("./path.json","w") do |f|
  f.puts JSON.pretty_generate(header)
 end