需要解析Jenkins Pipeline中的JSON文件

xoshrz7s  于 2022-12-27  发布在  Jenkins
关注(0)|答案(2)|浏览(245)

我正在通过Jenkins Pipeline脚本生成一个json输出文件。我需要通过Jenkins Pipeline脚本进一步解析JSON文件,以从下面的json文件中获取关键属性,如总事件数、总发生次数、类型、策略和每个事件的文件名。
JSON文件,

{
    "id": "/var/lib/jenkins/workspace/sample",
    "type": "path_scan",
    "entities_with_incidents": [{
        "mode": "FILE",
        "filename": "/var/lib/jenkins/workspace/sample/fakesecret.txt",
        "incidents": [{
            "policy": "Secrets detection",
            "occurrences": [{
                "match": "234ae*****************5q345",
                "type": "apikey",
                "line_start": 2,
                "line_end": 2,
                "index_start": 22,
                "index_end": 49,
                "pre_line_start": 2,
                "pre_line_end": 2
            }],
            "type": "Generic High Entropy Secret",
            "validity": "no_checker",
            "ignore_sha": "16b4ab506f666f1d58d7f0b70c65e8036d0922c59023f6815b832b6d6465e670",
            "total_occurrences": 1
        }],
        "total_incidents": 1,
        "total_occurrences": 1
    }, {
        "mode": "FILE",
        "filename": "/var/lib/jenkins/workspace/sample/config.py",
        "incidents": [{
            "policy": "Secrets detection",
            "occurrences": [{
                "match": "ALKS*************4SDA",
                "type": "apikey",
                "line_start": 2,
                "line_end": 2,
                "index_start": 22,
                "index_end": 43,
                "pre_line_start": 2,
                "pre_line_end": 2
            }],
            "type": "Generic High Entropy Secret",
            "validity": "no_checker",
            "ignore_sha": "7ef2d76f21eacc87dbca2de386bebb2b7cf114d6bc5418ba7a36ef5084119054",
            "total_occurrences": 1
        }],
        "total_incidents": 1,
        "total_occurrences": 1
    }],
    "total_incidents": 2,
    "total_occurrences": 2,
    "secrets_engine_version": "2.81.0"
}
bt1cpqcv

bt1cpqcv1#

您可以使用Python加载json.txt文件并将其转换为字典

import json
 
with open('json.txt') as json_file:
    data = json.load(json_file)
    print(data["type"]) # path_scan will be printed
s5a0g9ez

s5a0g9ez2#

您可以使用readJSON步骤(用于阅读json文件或字符串),它将解析json,并且您将能够通过名称或索引访问属性。
这是它的文档:https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

相关问题