param_types.py 500 B

123456789101112131415161718192021
  1. import json
  2. from typing import Any, Optional
  3. import asyncclick as click
  4. class JsonParamType(click.ParamType):
  5. name = "json"
  6. def convert(self, value, param, ctx) -> Optional[dict[str, Any]]:
  7. if value is None:
  8. return None
  9. if isinstance(value, dict):
  10. return value
  11. try:
  12. return json.loads(value)
  13. except json.JSONDecodeError:
  14. self.fail(f"'{value}' is not a valid JSON string", param, ctx)
  15. JSON = JsonParamType()