Skip to content
Advertisement

Python jsonschema, allowing nothing, or require one and only one of two fields

I am working with jsonschema for Python and I am trying to allow any of the following:

{}
# or
{
    'id': 'd6a4def3-4a6a-4fb4-a38e-f98ea48f708a'
}
# or
{
    'status': 'Done'
}

but I don’t want to allow the following because both fields are provided:

{
    'id': 'd6a4def3-4a6a-4fb4-a38e-f98ea48f708a',
    'status': 'Done'
}

This is what I have so far which allows one field or the other to be provided like I want but it doesn’t allow nothing.

GET_CALL = {
    "type": "object",
    "additionalProperties": False,
    "properties": {
        "id": {
            "type": "string",
            "pattern": REGEX_EXPRESSIONS['UUID4'], # Matches a UUID4 format
        },
        "status": {
            "type": "string",
            "enum": ["Done", "Ready"],
        },
    },
    "oneOf": [ # This makes it so I can only have one or the other but it doesn't allow nothing.
        {"required": ["id"]},
        {"required": ["status"]}
    ],
}

Advertisement

Answer

You need your oneOf to cover all cases. Luckily this is not too complex.

Here’s the schema you need for just what you’ve specified. You can work that into your existing schema.

{
  "oneOf": [
    {
      "additionalProperties": false
    },
    {
      "required": [
        "id"
      ]
    },
    {
      "required": [
        "status"
      ]
    }
  ]
}

(draft-7 JSON Schema)

You can test it at jsonschema.dev (link is pre-loaded with this schema and a test instance)

To clarify, you’ll still need type: object.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement