How to validate a list of dictionaries using jsonschema with Python

Viewed 255

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 Answers

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.

Related