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

守給你的承諾、 提交于 2019-12-02 21:15:24

问题


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"
    }
}

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.


回答1:


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

You'll get the nice hash

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

And, you can iterate over it:

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



来源:https://stackoverflow.com/questions/32560081/iterate-json-with-ruby-and-get-a-key-value-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!