jayveersolanki
jayveersolanki

Reputation: 92

How to remove empty objects and array from JSON?

{
    "_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?

Upvotes: 0

Views: 826

Answers (2)

Olvin Roght
Olvin Roght

Reputation: 7812

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

Upvotes: 1

balderman
balderman

Reputation: 23825

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

Upvotes: 1

Related Questions