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

Groovy从嵌套JSON数组提取值时父级ID引用错误问题求助

问题根源

你的原代码直接全局提取events/lots/pricings三个层级的数组,完全丢失了嵌套结构的上下文关联,无法对应到每个pricing条目所属的上级lot和event:

  • i_events.collect{it.id}[0] 永远只能取到第一个event的ID
  • i_lots.collect{it.id}[1] 取的是所有lot的ID集合的第二个元素,和pricing所属的lot没有任何关联

解决思路

逐层遍历嵌套结构,每一层遍历都保留上层的ID信息,不要直接全局拉平子数组。Groovy可以用collectMany直接展开下层返回的集合,避免多层嵌套数组的问题。

正确实现代码

def body = message.getBody(String.class)
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(body)

// 如果你需要所有pricing统一绑定第一个event的id,就把下面的eventId换成 def eventId = object.events[0].id
def o_values = object.events.collectMany { event ->
    def eventId = event.id
    event.lots.collectMany { lot ->
        def lotId = lot.id
        lot.pricings.collect { pricing ->
            "('${eventId}','${lotId}','${pricing.id}','${pricing.name}')"
        }
    }
}.join(',')

// 测试打印
println o_values

输出说明

如果保留取当前所属event ID的逻辑,运行示例输入得到的输出为:

('event_id1','id3','p id1','TEST 1'),('event_id2','id A','p id2','TEST 2')

如果需要匹配你给出的期望输出(所有pricing都绑定第一个event的ID),只要把代码里的eventId赋值替换为注释里的固定取值即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:36:03