2

I have a list of dictionaries like this:

list_of_dictionaries = [{'key1': True}, {'key2': 0.2}]

And I want to validate it using jsonschema package.

I created a schema like this:

schema = {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "key1": {
                "type": "boolean"
            },
            "key2": {
                "type": "number"
            }
        },
        "required": ["enabled"]
    }
}

But it is not correct for my list because to make it works my list should be like this:

list_dict = [{'key1': True, 'key2': 0.5}]

How can I create a correct schema to validate my list? Thank you in advance.

1 Answers1

5

I think you might want to be using the oneOf construct. Basically, you're trying to describe a list that can contain any number of two different kinds of objects.

Here's an example of use:

{
  "type": "array",
  "items": {
    "$ref": "#/defs/element"
  },
  "$defs": {
    "element": {
      "type": "object",
      "oneOf": [
        {
          "$ref": "#/$defs/foo"
        },
        {
          "$ref": "#/$defs/bar"
        }
      ]
    },
    "foo": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "key1": {
          "type": "boolean"
        }
      },
      "required": [
        "key1"
      ]
    },
    "bar": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "key2": {
          "type": "boolean"
        }
      },
      "required": [
        "key2"
      ]
    }
  }
}

There are also anyOf and allOf combiners that might be useful to you. Take a look at jsonschema's documentation on combining for more information.

Jonathan Mayer
  • 132
  • 1
  • 5
  • 1
    As a note, `oneOf` will only work if the value schemas are mutually exclusive, which might require the use of `additionalProperties: false` to achieve. This answer is good. – Relequestual Feb 02 '22 at 09:01
  • 1
    In the above example, "required" is doing the heavy lifting to distinguish the types, but I added "additionalProperties" to the example because I think you're right, it's better form. – Jonathan Mayer Feb 03 '22 at 22:31