Validator class¶
- class rapidjson.Validator(json_schema)¶
- Parameters
json_schema – the JSON schema, specified as a
strinstance or an UTF-8bytesinstance- Raises
JSONDecodeError – if json_schema is not a valid
JSONvalue
- __call__(json)¶
- Parameters
json – the
JSONvalue, specified as astrinstance or an UTF-8bytesinstance, that will be validated- Raises
JSONDecodeError – if json is not a valid
JSONvalue
The given json value will be validated accordingly to the schema: a
ValidationErrorwill be raised if the validation fails, and the exception will contain three arguments, respectively the type of the error, the position in the schema and the position in theJSONdocument where the error occurred:>>> validate = Validator('{"required": ["a", "b"]}') >>> validate('{"a": null, "b": 1}') >>> try: ... validate('{"a": null, "c": false}') ... except ValidationError as error: ... print(error.args) ... ('required', '#', '#')
>>> validate = Validator('{"type": "array",' ... ' "items": {"type": "string"},' ... ' "minItems": 1}') >>> validate('["foo", "bar"]') >>> try: ... validate('[]') ... except ValidationError as error: ... print(error.args) ... ('minItems', '#', '#')
>>> try: ... validate('[1]') ... except ValidationError as error: ... print(error.args) ... ('type', '#/items', '#/0')
When json is not a valid JSON document, a
JSONDecodeErroris raised instead:>>> validate('x') Traceback (most recent call last): File "<stdin>", line 1, in <module> rapidjson.JSONDecodeError: Invalid JSON