[英]jsonschema does not validate json correctly
我正在尝试在我的 Python 代码中使用jsonchema验证 JSON 文件,但是,我遇到了一个我无法理解的错误。
from jsonschema import validate
import json
point_schema = {
"$id": "https://example.com/schemas/point",
"type": "object",
"properties": {"x": {"type": "number"}, "y": {"type": "number"}},
"required": ["x", "y"],
}
polygon_schema = {
"$id": "https://example.com/schemas/polygon",
"type": "array",
"items": {"$ref": "https://example.com/schemas/point"},
}
a_polygon = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, {'x': 1, 'y': 2}]
a_polygon_json = json.JSONEncoder.encode(a_polygon)
validate(instance=a_polygon_json, schema=polygon_schema)
在这里,我定义了一个point
和一个polygon
模式。 基本上, polygon
应该是一个points
组。 如您所见,我的a_polygon
是一个数组。
但是,由于我无法理解的原因, jsonschema
并没有以同样的方式看待它:
>>> validate(instance=a_polygon_json, schema=polygon_schema)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/anaconda3/envs/darwin-py/lib/python3.7/site-packages/jsonschema/validators.py", line 934, in validate
raise error
jsonschema.exceptions.ValidationError: '[{"x": 1, "y": 2}, {"x": 3, "y": 4}, {"x": 1, "y": 2}]' is not of type 'array'
Failed validating 'type' in schema:
{'$id': 'https://example.com/schemas/polygon',
'items': {'$ref': 'https://example.com/schemas/point'},
'type': 'array'}
On instance:
'[{"x": 1, "y": 2}, {"x": 3, "y": 4}, {"x": 1, "y": 2}]'
我究竟做错了什么?
我认为你不想做json.JSONEncoder.encode
。 这样做会将数据结构转换为实例的字符串表示形式。 根据文档中的示例,JSON 架构实现需要未编码的 JSON 实例。
validate(instance={"name": "Eggs", "price": 34.99}, schema=schema)
https://github.com/Julian/jsonschema
您看到的错误是“字符串不是数组”,这是真的。 容易犯错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.