Bootstrap FreeKB - Python (Scripting) - Determine if JSON key contains an empty list
Python (Scripting) - Determine if JSON key contains an empty list

Updated:   |  Python (Scripting) articles

Let's say you have the following JSON. Notice that the foo key contains an empty list, as indicated by the [ ] characters.

{ 
 "foo": []
}

 

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).

And you are parsing the JSON using json.load or using json.loads, perhaps like this.

#!/usr/bin/python3
import json
raw_json = '{ "foo": [] }'

try:
  parsed_json = json.loads ( raw_json )
except Exception as exception:
  print(f"Got the following exception: {exception}")

print(parsed_json)

 

An if statement can be used to determine if the list is empty.

#!/usr/bin/python3
import json
raw_json = '{ "foo": [] }'

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")

 

Running this Python script should return the following.

~]$ python example.py
The foo 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")

 

Running this Python script should return the following.

~]$ python example.py
The foo key does NOT contain an empty list

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 0b73f1 in the box below so that we can be sure you are a human.