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

Groovy中如何通过子属性查找JSON根元素并获取对应属性值

在Groovy中查找指定条件的JSON元素并获取对应值

我来给你展示几种简洁的实现方式,Groovy对集合和JSON的处理优势在这儿就能体现出来~

首先,我们先明确原始的JSON数据:

{"mom": [{"height": 1, "weight": 2}], "dad": [{"height": 2, "weight": 3}]}

方法一:遍历根元素匹配条件

这种方法逻辑直观,适合新手理解:

import groovy.json.JsonSlurper

// 原始JSON字符串
def jsonStr = '''{"mom": [{"height": 1, "weight": 2}], "dad": [{"height": 2, "weight": 3}]}'''
// 解析JSON为Groovy原生的数据结构(Map<List<Map>>)
def parsedJson = new JsonSlurper().parseText(jsonStr)

// 遍历每个根键值对,找到包含height=2的子对象的根元素
def matchEntry = parsedJson.find { rootKey, childList ->
    // 检查当前根元素下的列表中是否存在height为2的对象
    childList.any { it.height == 2 }
}

if (matchEntry) {
    def targetRoot = matchEntry.key // 获取根元素名:dad
    // 从匹配的列表中取出目标对象的weight值
    def targetWeight = matchEntry.value.find { it.height == 2 }.weight
    println "匹配的根元素:*$targetRoot*"
    println "对应的weight值:*$targetWeight*"
} else {
    println "未找到height值为2的子对象"
}

方法二:扁平化后匹配(更简洁的链式调用)

如果你喜欢更紧凑的写法,可以把所有根键和子对象的组合扁平化后再查找:

import groovy.json.JsonSlurper

def jsonStr = '''{"mom": [{"height": 1, "weight": 2}], "dad": [{"height": 2, "weight": 3}]}'''
def parsedJson = new JsonSlurper().parseText(jsonStr)

// 把每个根键和对应的子对象展开成[根键, 子对象]的集合,再查找符合条件的项
def (rootKey, targetObj) = parsedJson.collectMany { key, list ->
    list.collect { [key, it] }
}.find { _, obj -> obj.height == 2 } ?: [null, null]

if (rootKey && targetObj) {
    println "根元素:*$rootKey*"
    println "weight值:*${targetObj.weight}*"
} else {
    println "没有找到符合条件的元素"
}

注意事项

  • 如果你的JSON数据是从文件或网络读取的,只需要把parseText换成对应的parse方法(比如parse(new File("data.json")))即可。
  • 如果存在多个根元素包含height=2的子对象,把find换成findAll就能得到所有匹配项,再遍历处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:09:05