"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

Answer from Matt Varblow on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › check-if-python-json-object-is-empty
Check If Python Json Object is Empty - GeeksforGeeks
July 23, 2025 - JSON object 1 is empty. JSON object 2 is not empty. {'title': 'Introduction to Python', 'author': 'GeeksforGeeks', 'topics': ['Basics', 'Data Structures', 'Functions', 'Modules']}
🌐
FreeKB
freekb.net › Article
Determine if JSON key contains an empty list
On the other hand, if the list is not empty. #!/usr/bin/python3 import json raw_json = '{ "foo": [ "Hello", "World" ] }' try: parsed_json = json.loads ( raw_json ) except Exception as exception: print(f"Got the following exception: {exception}") if len(parsed_json['foo']) == 0: print("The foo key contains an empty list") else: print("The foo key does NOT contain an empty list")
🌐
Wikimedia Phabricator
phabricator.wikimedia.org › T12887
T12887 API JSON formatter returns [] as an empty return value - inconsistent with {} for non-empty values
Just to clarify on this old bug -- the Python JSON interpreter can handle [] just fine, but it creates a *list* (equivalent to JS *array*) instead of a *dict* (equivalent to JS *object*).
🌐
Quora
quora.com › How-do-you-declare-an-empty-JSON-in-Python
How to declare an empty JSON in Python - Quora
An empty string is not a valid JSON representation of anything. If you try to decode an empty string using Python's standard [code ]json[/code] module, you'll get an error: [code]>>> import j...
Find elsewhere
🌐
Example Code
example-code.com › python › json_insert_empty_array_or_object.asp
CkPython JSON Insert Empty Array or Object
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
Top answer
1 of 3
2

You're misunderstanding how in works. in checks to see if a key exists in a dictionary, it does not index into a dictionary. That's what the square brackets do.

if 'title_jpn' in json_data['gmetadata'][0] is not "":

The above line will not evaluate as you expect. It should be.

if json_data['gmetadata'][0]['title_jpn'] is not "":

This can be further simplified because empty strings '' always evaluate to False in python. So instead of checking if the string is not empty, just check if it has any value at all like the following:

if json_data['gmetadata'][0]['title_jpn']:

If you're trying to guard against the fact that title_jpn might be optional and not always exist, you need to do two conditions in your if statement (which I think is what you were originally trying to do):

if 'title_jpn' in json_data['gmetadata'][0] and json_data['gmetadata'][0]['title_jpn']:

The above line first checks if the title_jpn key is present before trying to check if it's value is empty. This can be further simplified using the dictionary .get() method which allows you to supply a default.

if json_data['gmetadata'][0].get('title_jpn', None):

The above will check if title_jpn is in the dictionary and return the value if it does, or None as a default if it does not. Since None is interpreted as False in python, the if block will not run, which is the desired behaviour.

dict.get(key, default=None)

However, since .get() automatically sets the default value to None, you can simply do the following.

if json_data['gmetadata'][0].get('title_jpn'):
2 of 3
0

Your .get won't work, since this applies to dictionaries. As far as I know, "In" won't work either since this is the syntax for a For loop. Probably you want the "Find" method, since this matches a substring within a longer string (which is your goal, if I understand correctly). It'll return minus one if the string isn't found. So in your case, example use:

if json_data['gmetadata'][0].find('title_jpn') != -1:
🌐
Community
community.safe.com › transformers-9 › how-to-remove-empty-property-from-a-json-with-python-4004
how to remove empty property from a json with python | Community
June 29, 2017 - # PythonCaller Script Example import json def remove_null(feature): array = json.loads(feature.getAttribute('_result')) for m in array: for k, v in m['attributes'].items(): if v == None or v == '': del m['attributes'][k] feature.setAttribute('_result_bis', json.dumps(array)) BTW, why not use the JSONFormatter?
Top answer
1 of 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
2 of 2
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