You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Groovy向现有JSON文件追加模块条目?

Fixing Groovy JSON Module Appending Issue

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 json object's modules list (which is a Groovy List under the hood) by calling add() with our new module Map.
  • We don't need to use JsonBuilder for the new module—Groovy's native Map will serialize correctly to JSON when we use JsonOutput.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:09:19