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.