'Set default values according to JSON schema automatically
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!
Solution 1:[1]
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.
Solution 2:[2]
---- Edited ----
You can use the jsonschema_default
package linked below to generate a default JSON object from your JSON schema.
https://pypi.org/project/jsonschema-default/
Then you can use the default JSON object to fill in the missing key in your json_dict
Like so:
import jsonschema_default as jd
default_obj = jd.create_from("./data_schema_example.json")
for key in default_obj.keys():
if key not in json_dict:
json_dict[key] = default_obj[key]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ether |
Solution 2 |