Skip to content

Instantly share code, notes, and snippets.

@wrouesnel
Created March 19, 2022 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrouesnel/8d14a887455606342bb94099585f627d to your computer and use it in GitHub Desktop.
Save wrouesnel/8d14a887455606342bb94099585f627d to your computer and use it in GitHub Desktop.
An action implementing key=<json> parsing
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