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

Groovy JsonBuilder构建多地区工位JSON结构出错求助

预期JSON格式

我拥有地点列表和工位列表,期望生成如下结构的JSON:

{
    "Company": "my company",
    "Locations": {
        "India": {
            "cubicals": [
                "A-8954","B-3212"
            ]
        },
        "USA": {
            "cubicals": [
                "A-8954","B-3212"
            ]
        }
    }
}
编写的Groovy代码

cubicalList和nationsList已定义,原代码如下:

cubicalList=["A-8954","B-3212"]
nationsList=["India", "USA"]
def json = new groovy.json.JsonBuilder()
name="my company"
json {
    company name
    Locations {
            "${nationsList}" (
            {
                cubicals cubicalsList
            }
            )
    }
}

println json.toPrettyString()
问题描述

当前代码生成的结果将India和USA合并为一个键,而非作为Locations下的独立键,错误输出如下:

{
    "company": "my company",
    "Locations": {
        "[India, USA]": {
            "cubicals": [
                "A-8954",
                "B-3212"
            ]
        }
    }
}
解决方案

问题根源是直接将整个nationsList作为键名,Groovy会把列表转为字符串[India, USA]作为单个键。需要遍历国家列表,为每个国家单独生成键值对,同时修正原代码的笔误和键名大小写问题:

修复后的代码

cubicalList=["A-8954","B-3212"]
nationsList=["India", "USA"]
def json = new groovy.json.JsonBuilder()
name="my company"
json {
    Company name  // 修正键名大小写,匹配预期的"Company"
    Locations {
        // 遍历每个国家,生成独立的键值对
        nationsList.each { nation ->
            "$nation" {
                cubicals cubicalList
            }
        }
    }
}

println json.toPrettyString()

关键修正点

  • 用each循环遍历nationsList,为每个国家创建Locations下的独立键
  • 修正原代码中company的大小写,使其与预期的Company键名一致
  • 修正原代码中的笔误:将cubicalsList改为正确的变量名cubicalList

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:15:01