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

Groovy动态构建JSON:如何将多组键值对存入同一JSON对象

解决Groovy构建JSON时数组转对象的问题

作为Groovy脚本新手,我想通过API查询响应构建JSON输出,因为需要多次查询动态生成JSON文件,所以用了Map。我希望把多组键值对存入同一个JSON对象里,但当前代码生成的是数组结构,不符合预期。

当前代码

def map = [
    'result': []
]

def response = /* 发起API请求 */

map.result << [respose_key1_1: "response_value 1_1"]
map.result << [response_key1_2: "response_value 1_2"]

def json = new JsonBuilder()

json rootKey: map

println JsonOutput.prettyPrint(json.toString())

当前输出

{
    "rootKey": {
        "result": [
            {
                "respose_key1_1": "response_value 1_1"
            },
            {
                "response_key1_2": "response_value 1_2"
            }
        ]
    }
}

期望输出

{
    "rootKey": {
        "result": {
            "respose_key1_1": "response_value 1_1",
            "response_key1_2": "response_value 1_2"
        }
    }
}

解决方案

问题出在初始化map时,把result定义成了数组([]),而我们需要的是对象(Map,用[:]表示)。修改方式如下:

  1. 初始化result为空Map:'result': [:]
  2. 添加键值对时,直接给Map赋值,而不是用<<追加数组元素

修改后的代码:

def map = [
    'result': [:] // 这里改成空Map
]

def response = /* 发起API请求 */

// 直接给result的键赋值
map.result.respose_key1_1 = "response_value 1_1"
map.result.response_key1_2 = "response_value 1_2"

// 或者用put方法,适合键名带特殊字符的情况
// map.result.put("respose_key1_1", "response_value 1_1")
// map.result.put("response_key1_2", "response_value 1_2")

def json = new JsonBuilder()

json rootKey: map

println JsonOutput.prettyPrint(json.toString())

这样运行后,result就会是一个包含所有键值对的JSON对象,符合期望输出。

内容的提问来源于stack exchange,提问作者Zepperoni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:20:07