Bootstrap FreeKB - Python (Scripting) - Pass argparse into JSON
Python (Scripting) - Pass argparse into JSON

Updated:   |  Python (Scripting) articles

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

Here is an example of how you can use argparse to return a dictionary (key value pairs) and to then convert the dictionary into a JSON object using json.dumps and finally to parse the JSON into a format Python can interpret using json.loads.

#!/usr/bin/python3
import argparse
import json

parser = argparse.ArgumentParser()
parser.add_argument("--environment", action="store", required=True)
parser.add_argument("--platform",    action="store", required=True)

args = parser.parse_args()

argparse_dict = vars(args)
print(f"argparse_dict = {argparse_dict}")

try:
  raw_json = json.dumps(argparse_dict)
except Exception as exception:
  print(f"Got the following exception: {exception}")
else:
  print(f"raw json = {raw_json}")

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

 

Running this Python script should return the following. In this scenario, there are no differences between the raw JSON and the parsed JSON.

~]$ python testing.py --environment staging --platform aws
argparse_dict = {'environment': 'staging', 'platform': 'aws'}
raw json      = {"environment": "staging", "platform": "aws"}
parsed json   = {u'environment': u'staging', u'platform': u'aws'}

 




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