0

how can i loop through a json file using a FOR loop in groovy? I am able to do it with .each but i am in a situation/bug where i cannot use .each loops.

The json file is being read and parsed into an object.

The json looks like this:

{
    "workflows1": {
        "name": "/wf_multifolder",
        "file": "release1/wf_multifolder.XML",
        "folderNames": {
            "multifolder": "{{multifolder}}",
            "agent1": "{{agentx}}"
        }
    },
    "workflows2": {
        "name": "/wf_multifolder",
        "file": "release1/wf_multifolder.XML",
        "folderNames": {
            "multifolder": "{{multifolder}}",
            "agent1": "{{agentx}}"
        }
    }
}

Note: i can modify the json file, if need to make the process simpler.. All i am try to do is to loop throgh and extract the values for the keys.

2
  • Why can't you use each? Commented Apr 8, 2017 at 8:12
  • Because jenkins doesn't like each ... there is a limitation in this tool. I will paste the jira story # on this Commented Apr 8, 2017 at 12:18

1 Answer 1

1

So given the json in a String like so:

def jsonText = '''{
    "workflows1": {
        "name": "/wf_multifolder",
        "file": "release1/wf_multifolder.XML",
        "folderNames": {
            "multifolder": "{{multifolder}}",
            "agent1": "{{agentx}}"
        }
    },
    "workflows2": {
        "name": "/wf_multifolder",
        "file": "release1/wf_multifolder.XML",
        "folderNames": {
            "multifolder": "{{multifolder}}",
            "agent1": "{{agentx}}"
        }
    }
}'''

You can just do:

import groovy.json.*

def json = new JsonSlurper().parseText(jsonText)

for(entry in json) {
    println "$entry.key has file $entry.value.file"
}

to print:

workflows1 has file release1/wf_multifolder.XML
workflows2 has file release1/wf_multifolder.XML
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but i think i will need to use a counter, so that i can iterate through the values of the say, workflow1 and then workflows2 .... so on.
I thought using the for in looping would cause problems with CPS?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.