如何使用Groovy向现有JSON文件追加模块条目?
Hey there! I see where you're going wrong with your code—you're currently combining the original JSON object and your new module into a top-level array, which is why you're getting that unexpected output. Let's fix this by directly appending the new module to the existing modules array in your original JSON.
What's Wrong with Your Current Code?
Your code creates a separate jsonNew object with its own modules key, then wraps both the original JSON and this new object in an array with [json, jsonNew]. That's why your output is an array of two objects instead of updating the original modules array.
Corrected Code
Here's how to properly append the new module to your existing modules list:
def inputFile = new File("modules.json") def outputFile = new File("modules.new.json") // Parse the original JSON into a Groovy object def json = new JsonSlurper().parseText(inputFile.text) // Create the new module as a simple Map (no need for JsonBuilder here) def newModule = [ description: 'Module 4', type: 'TEST' ] // Append the new module to the existing modules array json.modules.add(newModule) // Convert the updated object back to pretty-printed JSON def prettyJson = JsonOutput.prettyPrint(JsonOutput.toJson(json)) // Print and write the result println "Updated JSON:\n" + prettyJson outputFile.text = prettyJson
Why This Works
- We directly modify the parsed
jsonobject'smoduleslist (which is a GroovyListunder the hood) by callingadd()with our new module Map. - We don't need to use
JsonBuilderfor the new module—Groovy's native Map will serialize correctly to JSON when we useJsonOutput.toJson().
Expected Output
Running this code will give you exactly the format you want:
{ "organisation": "company", "modules": [ { "description": "Module 1", "type": "Q1" }, { "description": "Module 2", "type": "Q2" }, { "description": "Module 3", "type": "Q3" }, { "description": "Module 4", "type": "TEST" } ] }
内容的提问来源于stack exchange,提问作者neil201

