groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From idioma <>
Subject Groovy script to replace Json values via a mapping file
Date Sat, 04 Jun 2016 23:02:49 GMT
I am fairly new to Groovy and I have been struggling with this task for a
while and wondered whether it can be easily achieved by using the
ConfigSlurper. I need to read a mapping file, which looks like the

A some text A2

(I can have some freedom in amending the internal structure of this
properties file)

I have then a JSON file that I read/parse with the JSON Slurper, which
presents the following structure:

      "field1": "A"
      "field2": "A", 
      "field3": "A" 


We are expecting to get the same value for field1 - field3 every time,
however the mappings should work as follows:

if field1 then no replacement should occur

if field2 has value A then substitute to "some text"

if field3 has value if A then substitute to A2

The mapping file has multiple lines containing different mix of values and
the maps are always conditionally decided according to the value of the
incoming JSON property, which matches to the left hand side value from the
properties file. 

I attempted the following when I initially tried to replace the original
value of field2 on the basis of a modified version of the mappings:

A someText
AF otherText
N3 againSomeText

Here is my attempt: 

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

class LoadConfigFileAndReplaceValues {

    static void main(String[] args) {

        def content = '''
        def slurper = new JsonSlurper().parseText(content)
        def builder = new JsonBuilder(slurper)

        def propertiesFile = new
        Properties props = new Properties()
        props.load(new FileInputStream(propertiesFile))
        def conf = new ConfigSlurper().parse(props).flatten();
        conf.each { k, v ->
            if (builder.content.field2) {
                builder.content.field2 = v
            println("This prints the resulting JSON :" +

I am returned with the following:

This prints the resulting JSON :{
    "field1": "A",
    "field2": "someText"
This prints the resulting JSON :{
    "field1": "A",
    "field2": "otherText"
This prints the resulting JSON :{
    "field1": "A",
    "field2": "againSomeText"

whereas I would need to be returned with the first mapping A = someText: 

This prints the resulting JSON :{
    "field1": "A",
    "field2": "someText"

I am not sure how I can achieve this and if the ConfigSlurper is the best
approach I can use to do lookups/mappings. Can you please advise? 

Thank you so much,


View this message in context:
Sent from the Groovy Users mailing list archive at

View raw message