Created
March 19, 2022 03:42
-
-
Save wrouesnel/8d14a887455606342bb94099585f627d to your computer and use it in GitHub Desktop.
An action implementing key=<json> parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import json | |
class KeyValueJsonAction(argparse.Action): | |
""" | |
Argparse action for generating dictionaries from key-value args with JSON support | |
""" | |
def __call__(self, parser, namespace, values, option_string=None): | |
result = {} | |
for entry in values: | |
key,value = entry.split("=",1) | |
# Try and load value as a JSON object. If that fails, treat it as a string. | |
try: | |
parsed_value = json.loads(value) | |
except json.JSONDecodeError: | |
parsed_value = value | |
result[key] = parsed_value | |
setattr(namespace, self.dest, result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment