Home > Net >  Groovy (jenkinsfile) - Parsing Json maintaining same order
Groovy (jenkinsfile) - Parsing Json maintaining same order

Time:11-24

First, thank you for reading and helping. I have this issue and can't find a way to solve it. So, I'm setting up a test pipeline using jenkinsfile with parameters to start the build. I have a json file with the list of the docker tags available from a project order by time (newest first) that I want to test. The json file is something like this:

[
    "tag1",
    "tag2",
    (...)
]

The objective is to have a list in groovy with the tags in the same order as they are in the file to be able to set them as parameters option for jenkins.

I've tried to use groovy.json.JsonSlurperClassic and groovy.json.JsonSlurper, but after the parsing the order of the tags is completely different. Any suggestions how to do it? Thank you.

CodePudding user response:

Solution

If you use the readJSON step from the Pipeline Utility Steps plugin you can load the JSON into an ArrayList by setting returnPojo=true which should maintain insert order.

node {
    def jsonArr = ['tag1','tag2','tag3']
    writeJSON file: 'output.json', json: jsonArr
    
    def props = readJSON file: 'output.json', returnPojo: true
    println (props instanceof java.util.ArrayList)
}

I am using writeJSON just to for example. You obviously don't need to write your file if it already exists

My assumption is that, possibly, you're loading the JSON file into a Map which does not maintain insert order. Granted, your JSON structure doesn't lend itself to be stored in a map

CodePudding user response:

Since json stores objects as unordered, it can be mixed during the access.

In order to make a work around, I would recommend that you can put all tags in an array. Arrays stored as ordered. Thus, your json can be like:

{ "myTags": ["tag1", "tag2", "tag3"] }
  • Related