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

JIRA Scriptrunner中Groovy如何通过给定值获取嵌套JSON(map)的key

Groovy嵌套JSON按值查询对应Key解决方案

错误原因说明

你之前编写的parsedjson['email']?.key返回null,是因为该写法是直接在JSON的顶层结构查找email键,而你的JSON顶层只有boston、chicago两个城市键,自然找不到对应值。你之前使用的parsedjson['chicago']['email']能正常返回结果,是Groovy对集合的自动投影特性,会提取chicago对应列表中所有元素的email字段组成新列表,该逻辑不能直接套用到顶层取值场景。

实现代码

第一步:JSON解析

首先使用Groovy内置的JsonSlurper解析JSON字符串:

import groovy.json.JsonSlurper

def json = '''{
     "boston": [
        {
          "name":"bob",
          "phone":"242 123123",
          "email": "bob@boston.com"
        },
        {
          "name":"alice",
          "phone":"212-123-345",
          "email": "alice@boston.com"
        }
     ],
     "chicago": [
        {
          "name":"charlie",
          "phone":"313-232-545",
          "email": "charlie@chicago.com"
        },
        {
          "name":"denise",
          "phone":"414-123-546",
          "email": "denise@chicago.com"
        }
     ]
}'''
def parsedJson = new JsonSlurper().parseText(json)

第二步:封装查询方法

单匹配结果场景(返回第一个符合条件的Key)

/**
 * 从嵌套JSON顶层查询匹配字段值对应的Key
 * @param jsonObj 解析后的JSON Map对象
 * @param matchField 匹配的字段名(比如name、email)
 * @param matchValue 匹配的字段值
 * @return 符合条件的顶层Key,无匹配时返回null
 */
def findTopLevelKeyByFieldValue(Map jsonObj, String matchField, def matchValue) {
    jsonObj.find { topKey, itemList ->
        itemList.any { item -> item[matchField] == matchValue }
    }?.key
}

多匹配结果场景(返回所有符合条件的Key列表)

def findAllTopLevelKeysByFieldValue(Map jsonObj, String matchField, def matchValue) {
    jsonObj.findAll { topKey, itemList ->
        itemList.any { item -> item[matchField] == matchValue }
    }*.key
}

使用示例

// 按name=bob查询对应顶层Key
def result1 = findTopLevelKeyByFieldValue(parsedJson, 'name', 'bob')
println result1 // 输出:boston

// 按email=charlie@chicago.com查询对应顶层Key
def result2 = findTopLevelKeyByFieldValue(parsedJson, 'email', 'charlie@chicago.com')
println result2 // 输出:chicago

// 多匹配场景测试
def result3 = findAllTopLevelKeysByFieldValue(parsedJson, 'name', 'bob')
println result3 // 输出:[boston]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:15:01