我对Groovy(和json)还很陌生,正在尝试使用这段代码,以使其正常工作,但还不太熟悉,需要一些帮助。。。
因此,我要做的是解析现有的json文件,然后添加/附加其他条目,如以下示例所示:
原始Json
{
"organisation": "company",
"modules": [
{
"description": "Module 1",
"type": "Q1",
},
{
"description": "Module 2",
"type": "Q2",
},
{
"description": "Module 3",
"type": "Q3",
}
]
}
新建Json
modules {
description 'Module 4'
type 'TEST'
}
预期最终输出
{
"organisation": "company",
"modules": [
{
"description": "Module 1",
"type": "Q1",
},
{
"description": "Module 2",
"type": "Q2",
},
{
"description": "Module 3",
"type": "Q3",
},
{
"description": "Module 4",
"type": "TEST",
}
]
}
我已经尝试了以下代码片段的许多变体,但仍然没有为我的预期输出获得正确的格式
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]))
其结果如下:
[
{
"organisation": "company",
"modules": [
{
"description": "Module 1",
"type": "Q1"
},
{
"description": "Module 2",
"type": "Q2"
},
{
"description": "Module 3",
"type": "Q3"
}
]
},
{
"modules": {
"description": "Module 4",
"type": "TEST"
}
}
]
如果您能帮我整理一下,我们将不胜感激。