Home > Mobile >  Need to parse JSON file from Jenkins Pipeline
Need to parse JSON file from Jenkins Pipeline

Time:12-26

I am generating a json output file through Jenkins pipeline script. I need to parse JSON file through Jenkins Pipeline script further to get the key attributes like total incidents, total occurrences, type,policy and filenames of each from below json file.

JSON File,

{
    "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"
}

CodePudding user response:

You can use Python to load the json.txt file and convert it to dictionary

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

CodePudding user response:

You can use the readJSON step (works for reading json files or strings). It will parse json, and you will be able to access attributes by names or indexes.

This is the documentation for it: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

  • Related