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

如何通过Jenkins Pipeline脚本解析JSON提取关键属性

Jenkins Pipeline解析JSON提取关键字段

以下是直接可用的Jenkins Pipeline脚本,用于解析你提供的JSON文件,提取所需的total incidents、total occurrences、type、policy及各文件filename等属性:

pipeline {
    agent any

    stages {
        stage('解析JSON文件') {
            steps {
                script {
                    // 读取JSON文件内容
                    def jsonContent = readFile file: '你的JSON文件路径.json'
                    // 解析JSON为Groovy对象
                    def jsonSlurper = new groovy.json.JsonSlurper()
                    def scanResult = jsonSlurper.parseText(jsonContent)

                    // 提取顶层汇总数据
                    def scanType = scanResult.type
                    def totalIncidents = scanResult.total_incidents
                    def totalOccurrences = scanResult.total_occurrences

                    echo "扫描类型: ${scanType}"
                    echo "总事件数: ${totalIncidents}"
                    echo "总出现次数: ${totalOccurrences}"

                    // 遍历每个有事件的文件,提取详细信息
                    scanResult.entities_with_incidents.each { entity ->
                        if (entity.mode == 'FILE') {
                            def filename = entity.filename
                            echo "\n文件路径: ${filename}"
                            echo "该文件事件数: ${entity.total_incidents}"
                            echo "该文件出现次数: ${entity.total_occurrences}"

                            // 遍历该文件的每个事件,提取策略和事件类型
                            entity.incidents.each { incident ->
                                def policy = incident.policy
                                def incidentType = incident.type
                                echo "  检测策略: ${policy}"
                                echo "  事件类型: ${incidentType}"
                                echo "  该事件出现次数: ${incident.total_occurrences}"
                            }
                        }
                    }
                }
            }
        }
    }
}

关键说明

  • 替换'你的JSON文件路径.json'为实际的JSON文件路径(比如/var/lib/jenkins/workspace/sample/scan_result.json)
  • 使用readFile读取文件内容,通过JsonSlurper将JSON字符串解析为可操作的Groovy对象
  • 顶层字段直接通过对象属性访问:scanResult.type、scanResult.total_incidents等
  • 遍历entities_with_incidents数组获取每个文件的信息,再嵌套遍历incidents数组提取事件的策略和类型

脚本输出示例

扫描类型: path_scan
总事件数: 2
总出现次数: 2

文件路径: /var/lib/jenkins/workspace/sample/fakesecret.txt
该文件事件数: 1
该文件出现次数: 1
  检测策略: Secrets detection
  事件类型: Generic High Entropy Secret
  该事件出现次数: 1

文件路径: /var/lib/jenkins/workspace/sample/config.py
该文件事件数: 1
该文件出现次数: 1
  检测策略: Secrets detection
  事件类型: Generic High Entropy Secret
  该事件出现次数: 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:21:12