Bootstrap FreeKB - Python (Scripting) - Determine if JSON key exists
Python (Scripting) - Determine if JSON key exists

Updated:   |  Python (Scripting) articles

Let's say you have the following JSON.

{ 
 "foo": "Hello World"
}

 

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": "Hello World" }'

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 a key exists.

#!/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 'foo' in parsed_json:
  print("The foo key exists")

 

Or using a try / except / else/ finally block.

#!/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}")

try:
  parsed_json['foo']
except KeyError:
  pass
else:
  print("The foo key exists")

 

Running this Python script should return the following.

~]$ python example.py
The foo key exists

 

Or like this, using not in.

#!/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 'bar' not in parsed_json:
  print("The bar key does not exist")

 

Let's say you have nested JSON, like this.

{
  "main":
  {
    "department":
    {
      "username": "john.doe"
    }
  }
}

 

Here is how you can return the value of the "username" key.

#!/usr/bin/python3
import json
 
file = open("/path/to/example.json")

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

file.close()

if "main" in parsed_json:
  print("the main key exists")
  if "department" in parsed_json['main']:
    print("the main.department key exists")
    if "username" in parsed_json['main']['department']:
      print("the main.department.username key exists")

 




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 2160d8 in the box below so that we can be sure you are a human.