0
{
    "_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun",
    "actions": [
        {
            "date": "xyz",
            "lastBuiltRevision": {
                "branch": [
                    {
                        "SHA1": "5213affe970c86cd6e13b9d0e52515ac53f46aae",
                        "name": "feature/demo"
                    }
                ]
            }
        },
        {},
        {},
        {},
        {
            "date": "abc",
            "lastBuiltRevision": {
                "branch": [
                    {
                        "SHA1": "ca7972a32cc28304c22c98ceabf8e349fbf1a100",
                        "name": "refs/remotes/xyz/feature/demo_xyz"
                    }
                ]
            }
        },
        {
      "_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"
    },
    {
      "_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"
    },
    {},
    {
      "_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"
    },
    {},
    {},
    {},
    {},
    {
      "_class": "org.marvelution.jji.export.ParentAction"
    }
    ]
}

JSON Object is too long for Jenkins multibranch pipeline so I have shared a few limited objects from JSON.

I need results like the below after excluding below listed Challenges:

Name: refs/remotes/xyz/feature/demo_xyz, SHA1: ca7972a32cc28304c22c98ceabf8e349fbf1a100

Above result, I get using the below code but for that, I have removed blank object and other objects which don't contain lastBuiltRevision

import JSON

with open('jenkinsBuild.json') as f:
    data = json.load(f)

branch_name="refs/remotes/xyz/feature/demo_xyz"

for actions in data['actions']:
    for branch_data in actions['lastBuiltRevision']['branch']:
        if branch_data['name'] == branch_name:
            print(f"Name: {branch_data['name']}, SHA1: {branch_data['SHA1']}")

Challenges:

  1. If an empty object is there in JSON how to ignore that?

  2. If JSON object doesn't contain lastBuiltRevision then how to ignore that object?

  3. If JSON contains an empty array then how to ignore that?

2
  • can you explain the code import JSON ? Commented Oct 15, 2021 at 6:04
  • 1
    How would you remove them if the data didn't come from JSON? Once it's been loaded, it's the same as any nested dict/list structure that you'd create in any other way. Commented Oct 15, 2021 at 6:07

2 Answers 2

1

You can try the below

data = {
  "_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun",
  "actions": [
    {
      "date": "xyz",
      "lastBuiltRevision": {
        "branch": [
          {
            "SHA1": "5213affe970c86cd6e13b9d0e52515ac53f46aae",
            "name": "feature/demo"
          }
        ]
      }
    },
    {
      
    },
    {
      
    },
    {
      
    },
    {
      "date": "abc",
      "lastBuiltRevision": {
        "branch": [
          {
            "SHA1": "ca7972a32cc28304c22c98ceabf8e349fbf1a100",
            "name": "refs/remotes/xyz/feature/demo_xyz"
          }
        ]
      }
    },
    {
      "_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"
    },
    {
      "_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"
    },
    {
      
    },
    {
      "_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"
    },
    {
      
    },
    {
      
    },
    {
      
    },
    {
      
    },
    {
      "_class": "org.marvelution.jji.export.ParentAction"
    }
  ]
}
branch_name="refs/remotes/xyz/feature/demo_xyz"
data['actions'] = [x for x in data['actions'] if x and 'lastBuiltRevision' in x and x['lastBuiltRevision']['branch'][0]['name'] == branch_name]
for x in data.get('actions'):
  entry = x['lastBuiltRevision']['branch'][0]
  print(f'Name: {entry["name"]}, SHA1: {entry["SHA1"]}')

output

Name: refs/remotes/xyz/feature/demo_xyz, SHA1: ca7972a32cc28304c22c98ceabf8e349fbf1a100
Sign up to request clarification or add additional context in comments.

4 Comments

I need output for a specific branch which I pass as branch_name variable in question.
@Jayveer code was modified.
code modified but the output was not as expected. I have mentioned what I need in the final output.
@Jayveer another code update was done.
1

Your code is absolutely okay, much better than example in answer you accepted. There're two ways to deal with such as cases: prevent exception or handle exception.

1. Prevent exception:

import json

with open('jenkinsBuild.json') as f:
    data = json.load(f)

branch_name = 'refs/remotes/xyz/feature/demo_xyz'

for actions in data['actions']:
    if 'lastBuiltRevision' in branch_data:  # empty dict doesn't have this key too
        for branch_data in actions['lastBuiltRevision']['branch']:
            if branch_data['name'] == branch_name:
                print('Name:', branch_data['name'], 'SHA1:', branch_data['SHA1'])

2. Handle exception:

import json

with open('jenkinsBuild.json') as f:
    data = json.load(f)

branch_name = 'refs/remotes/xyz/feature/demo_xyz'

for actions in data['actions']:
    try:
        for branch_data in actions['lastBuiltRevision']['branch']:
            if branch_data['name'] == branch_name:
                print('Name:', branch_data['name'], 'SHA1:', branch_data['SHA1'])
    except KeyError:  # if any of accessed keys doesn't exist
        pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.