[Python] Set default values according to JSON schema automatically

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    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:

    1. 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.
    ​
    1. I would like to have a method that transforms my json_dict into the following according to the default 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!

    Continue reading...

Compartilhe esta Página