Replies: 1 comment
|
For avoiding typos in Python-authored schemas, a project-local string enum works with from enum import Enum
import json
from jsonschema import Draft202012Validator
class Keyword(str, Enum):
TYPE = "type"
PROPERTIES = "properties"
REQUIRED = "required"
class JsonType(str, Enum):
OBJECT = "object"
INTEGER = "integer"
schema = {
Keyword.TYPE: JsonType.OBJECT,
Keyword.PROPERTIES: {"count": {Keyword.TYPE: JsonType.INTEGER}},
Keyword.REQUIRED: ["count"],
}
Draft202012Validator.check_schema(schema)
validator = Draft202012Validator(schema)
assert validator.is_valid({"count": 1})
assert not validator.is_valid({"count": "1"})
assert not validator.is_valid({})
print(json.dumps(schema)) # ordinary JSON string keys/values
Keep keyword names separate from type values, and include the vocabulary for the draft(s) your application supports. This is an authoring convention: imported JSON still needs validation and tests. In particular, This demonstrates an application-level approach; it does not explain the maintainers' internal design rationale or claim an official complete keyword enum. References: Python string enums, jsonschema validator API. AI-assisted response. Example executed with Python 3.14 and jsonschema 4.25.1, including serialization and the positive/negative assertions above. |
Uh oh!
There was an error while loading. Please reload this page.
I'm a new user and am somewhat vexed by the need to use explicit strings everywhere. seems like a likely case for bugs to hide in typos and the like. I would much rather have constants or str enums to use for all the reserved words of schemas.
I looked at the main repo and the docs for examples and I'm still seeing string literals. is that really the case that the code uses literals all the way down?
if so, is there a reason not to adopt static definitions for reserved words? if not, can anyone point me in the right direction?
many thanks!
All reactions