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

Jenkins Pipeline中按键值对查找JSON数组元素并获取对应值

Jenkins Pipeline 查找指定DNS记录的Line值

假设你的DNS记录JSON结构类似这样:

{
  "records": [
    {
      "name": "example1.domain.tld.",
      "type": "A",
      "Line": "123"
    },
    {
      "name": "example2.domain.tld.",
      "type": "A",
      "Line": "456"
    },
    {
      "name": "example2.domain.tld.",
      "type": "CNAME",
      "Line": "789"
    }
  ]
}

可以用Groovy的find方法替代数组索引,直接筛选同时匹配name和type的首个记录,示例Pipeline代码如下:

// 读取并解析JSON数据(如果是文件可改用readJSON file: 'path/to/dns.json')
def dnsData = readJSON text: '''
{
  "records": [
    {
      "name": "example1.domain.tld.",
      "type": "A",
      "Line": "123"
    },
    {
      "name": "example2.domain.tld.",
      "type": "A",
      "Line": "456"
    },
    {
      "name": "example2.domain.tld.",
      "type": "CNAME",
      "Line": "789"
    }
  ]
}
'''

// 筛选符合条件的首个记录
def targetRecord = dnsData.records.find { record ->
    record.name == "example2.domain.tld." && record.type == "A"
}

// 输出结果,增加空值判断避免报错
if (targetRecord) {
    echo "匹配记录的Line值:${targetRecord.Line}"
} else {
    echo "未找到满足条件的DNS记录"
}

关键说明

  • readJSON:Jenkins Pipeline内置步骤,负责将JSON文本/文件转换为Groovy可操作的对象
  • find:Groovy集合方法,遍历数组并返回第一个满足闭包条件的元素,完全摆脱对数组索引的依赖
  • 空值判断:防止因找不到匹配记录导致后续代码抛出空指针异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:29:56