使用Ruby迭代JSON并获取数组中的键值

问题描述:

我在使用这个JSON时遇到了一些麻烦:

I'm getting some trouble with this 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值,在示例中有两个列表,但实际上有几十个。目的是了解将哪个工件部署到其自己的路径。例如:

I'm trying to iterate through the lists to get the PATH and the ARTIFACTS values for each list, in the example there are two lists, but really there are dozens. The purpose is to know which artifact is going to be deployed to its own path. For example:

/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

在我深入搜索后,我仍无法得到解决方案。

After I searched deeply I still cannot get the solution.

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

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

You'll get the same output, which you provided in the question