2

I'm pretty new to Groovy (and json) and being playing around with this code trying to get it to work, almost but not quite getting there and need a little help...

So what I'm trying to do is parse an existing json file and then add/append additional entries as in below example:

Original Json

{
  "organisation": "company",
  "modules": [
    {
        "description": "Module 1",
        "type": "Q1",
    },
    {
        "description": "Module 2",
        "type": "Q2",
    },
    {
        "description": "Module 3",
        "type": "Q3",
    }
  ]
}

New Json

modules {
        description 'Module 4'
        type 'TEST'
}

Intended Final Output

{
  "organisation": "company",
  "modules": [
    {
        "description": "Module 1",
        "type": "Q1",
    },
    {
        "description": "Module 2",
        "type": "Q2",
    },
    {
        "description": "Module 3",
        "type": "Q3",
    },
    {
        "description": "Module 4",
        "type": "TEST",
    }
  ]
}

I've tried many variations on the following code snippet but still not quite getting the right format for my intended output

def inputFile = file("modules.json")
def outputFile = new File("modules.new.json")
def json = new JsonSlurper().parseText(inputFile.text)

println "This is our original input JsonSlurper: \n"
println JsonOutput.prettyPrint(JsonOutput.toJson (json))

def builder = new JsonBuilder()
def jsonNew = builder {
    modules {
        description 'Module 4'
        type 'TEST'
      }
    }

println "This is our combined output JsonBuilder: \n"
println JsonOutput.prettyPrint(JsonOutput.toJson ([json, jsonNew]))

Which results in the below:

[
  {
    "organisation": "company",
    "modules": [
        {
            "description": "Module 1",
            "type": "Q1"
        },
        {
            "description": "Module 2",
            "type": "Q2"
        },
        {
            "description": "Module 3",
            "type": "Q3"
        }
    ]
  },
  {
    "modules": {
        "description": "Module 4",
        "type": "TEST"
    }
  }
]

Any help sorting this would be much appreciated.

2 Answers 2

1

You need to merge maps before produce json:

json.modules = json.modules << jsonNew.modules
println JsonOutput.prettyPrint(JsonOutput.toJson(json))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that, thought it would be something simple like merging them. However its still not quite there, why does it wrap the entire json as though its an array [ ] ?
0

[json, jsonNew] this just creates an array of objects, it's not adding the new object into the json.modules array.

Comments

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.