用 Ruby 迭代 JSON 并得到一个数组中的键,值

Iterate JSON with Ruby and get a key,value in an array

我遇到了一些麻烦 JSON:

{
    "ENAX-BRANCHESM-10" :
    {
        "repo":"test-ASO",
        "PATH":"/tmp/pruebaAlvaro",
        "ARTIFACTS":"example1.jar,another_one.jar,and_another.jar",
        "uri":"http://server:8081/artifactory/test-ASO",
        "created":"A705663"

    },
    "QZQP-QZQPMAN-16" : {
        "repo": "test-ASO",
        "PATH": "/tmp/pruebaAlvaro2",
        "ARTIFACTS": "test543.jar,thisisa.jar,yesanother.jar",
        "uri": "http://server:8081/artifactory/test-ASO",
        "created": "A705663"
    }
}

我正在尝试遍历列表以获取每个列表的 PATH 和 ARTIFACTS 值,在示例中有两个列表,但实际上有几十个。目的是了解哪个工件将被部署到它自己的路径。例如:

/tmp/pruebaAlvaro
example1.jar

/tmp/pruebaAlvaro 
another_one.jar

/tmp/pruebaAlvaro 
and_another.jar

/tmp/pruebaAlvaro2 
test543.jar

/tmp/pruebaAlvaro2 
thisisa.jar

/tmp/pruebaAlvaro2 
yesanother.jar

我深入搜索后仍然没有得到解决方案。

json = JSON.parse(your_json)
values = json.map { |_, v| { v[:PATH] => v[:ARTIFACTS].split(',') } }

你会得到很好的散列

{
  '/tmp/pruebaAlvaro' => ['example1.jar', 'another_one.jar', ...],
  '/tmp/pruebaAlvaro2' => [...]
}

并且,您可以对其进行迭代:

values.each do |path, artifacts|
  artifacts.each do |artifact|
    puts path
    puts artifact
  end
  puts
end

您将获得与您在问题中提供的相同的输出