I am using the jsonschema
package in python
to validate my JSONs. I can set default
in jsonschema
. Let us assume the following schema:
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"key_1": {},
"key_2": {
"type": "string",
"default": "do_not_overwrite_if_key_exists",
},
"key_3": {
"type": "string",
"default": "use_it_if_key_does_not_exist",
},
},
"required": ["key_1"],
}
json_dict = {"key_1": "key_1_value", "key_2": "key_2_value"}
validate(json_dict, schema)
My json_dict
is perfectly valid. I have two questions:
- Is the
default
keyword really so "useless" as the documentation (see below) says? This is all you get?
The “default” keyword doesn’t have an effect, but is nice to include for readers of the schema to more easily recognize the default behavior.
- I would like to have a method that transforms my
json_dict
into the following according to thedefault
keyword. Do you know of such a package?
json_dict = {"key_1": "key_1_value", "key_2": "key_2_value", "key_3": "use_it_if_key_does_not_exist"}
Thanks!
CodePudding user response:
The default
keyword is documented here: https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.2
It is indeed not a validation keyword, and only acts as an annotation. It is up to individual applications to decide how to use this annotation when it is generated from schema evaluation.