Json and dynamic variables

65 views
Skip to first unread message

Niksan

unread,
Feb 18, 2016, 5:04:45 AM2/18/16
to Jenkins Users
I have a job which has a groovy script and inside there I have a JSON like array which I parse, I'd like to offload this array to a JSON file on disk but it contains some elements that are gathered from parameters for the job.

What's the best way of injecting / replacing tokens in a JSON file that was loaded up in to a groovy script, are there any helpers already in Jenkins land to assist with this or would it be a case of traversing the whole array and manually replacing tokens with variables?

Ioannis Moutsatsos

unread,
Feb 18, 2016, 7:25:09 AM2/18/16
to Jenkins Users
I have been experimenting with the groovy JsonBuilder[1] and I find it quite capable in generating dynamic JSON. I'm not aware of any Jenkins plugin for what you are looking for though.

Cheers
Ioannis

Niksan

unread,
Feb 18, 2016, 9:47:11 AM2/18/16
to Jenkins Users
Thanks for that, I'm only interested in reading though, I came up with a solution although I'm rusty with Groovy but it will make do until a better approach appears.
This method enables me to write test json in the console for test purposes.

def token1 = 'Replaced-Token1'
def token2 = 'Replaced-Token2'

def tokenMapper = [
  '${token1}' : token1,
  '${token2}' : token2,
]

def jsonFile = new File('d:\\test.json').text
def json = new JsonSlurper().parseText(jsonFile)

json = json*.collectAll{
  element ->
  if(element instanceof String) {
    if(element.startsWith('${')) {
      element = tokenMapper[element] ?: element
    }
  }
  element
}

println(json)
 

Ioannis Moutsatsos

unread,
Feb 18, 2016, 9:57:36 AM2/18/16
to Jenkins Users
I see. In that case the 'groovy' way to do this is the SimpleTemplateEngine [1]


Hope it helps!
Ioannis

Niksan

unread,
Feb 18, 2016, 10:40:29 AM2/18/16
to Jenkins Users
Ah great, exactly what I was looking for, I also realised I'd also be better parsing the string before parsing the JSON, rather than the other way round,  simplifies it a lot. :)

Thanks again.
Reply all
Reply to author
Forward
0 new messages