如何从 jsonschema 检查数组中的项目,python3
How to check the items in array from a jsonschema, python3
我有一个 json 架构。这是在名为 input_schema.py
.
的文件中
input_scheme = {
"type": "object",
"properties": {
"company": {
"type": "object",
"properties": {
"founder": {"type": "string"},
"email": {"type": "string"},
},
},
"branch_locations": {
"type": "array",
"items": [
{
"street": {"type": "string"},
"house_number": {"type": "number"},
"city": {"type": "string"},
"country": {"type": "string"},
},
],
},
},
"additionalProperties": False,
}
我在另一个 python 文件中输入了数据。
from jsonschema import validate
from input_schema import input_scheme
data = {
"company": {
"founder": "me",
"email": "me@mycompany.com"
},
"branch_locations": [
{
"street": "Street A",
"house_number": 1,
"cityyyyyyy": "City A",
"country": "Country A",
},
],
}
validate(data, schema=input_scheme)
data
有一个奇怪的项目名称 "cityyyyyyy"
。这是一个无效的案例,但是 jsonschema
包中的 validate
函数无法检测到它。
我认为是 input_scheme
不正确。你能帮我吗?如何修改架构定义?顺便说一句,我需要一个分支位置的这 4 项(而且只有这 4 项):“街道”、“house_number”、“城市”、“国家”。
提前致谢。
items
关键字的值应该是模式。因为“street”、“house_number”等不是 JSON 架构关键字,所以它们会被忽略。并且没有对“branch_location”数组中的项目进行验证。
在您的示例中,items
关键字的值应如下所示。
{
"type": "object",
"properties": {
"street": { "type": "string" },
"house_number": { "type": "number" },
"city": { "type": "string" },
"country": { "type": "string" }
},
"additionalProperties": false
}
我有一个 json 架构。这是在名为 input_schema.py
.
input_scheme = {
"type": "object",
"properties": {
"company": {
"type": "object",
"properties": {
"founder": {"type": "string"},
"email": {"type": "string"},
},
},
"branch_locations": {
"type": "array",
"items": [
{
"street": {"type": "string"},
"house_number": {"type": "number"},
"city": {"type": "string"},
"country": {"type": "string"},
},
],
},
},
"additionalProperties": False,
}
我在另一个 python 文件中输入了数据。
from jsonschema import validate
from input_schema import input_scheme
data = {
"company": {
"founder": "me",
"email": "me@mycompany.com"
},
"branch_locations": [
{
"street": "Street A",
"house_number": 1,
"cityyyyyyy": "City A",
"country": "Country A",
},
],
}
validate(data, schema=input_scheme)
data
有一个奇怪的项目名称 "cityyyyyyy"
。这是一个无效的案例,但是 jsonschema
包中的 validate
函数无法检测到它。
我认为是 input_scheme
不正确。你能帮我吗?如何修改架构定义?顺便说一句,我需要一个分支位置的这 4 项(而且只有这 4 项):“街道”、“house_number”、“城市”、“国家”。
提前致谢。
items
关键字的值应该是模式。因为“street”、“house_number”等不是 JSON 架构关键字,所以它们会被忽略。并且没有对“branch_location”数组中的项目进行验证。
在您的示例中,items
关键字的值应如下所示。
{
"type": "object",
"properties": {
"street": { "type": "string" },
"house_number": { "type": "number" },
"city": { "type": "string" },
"country": { "type": "string" }
},
"additionalProperties": false
}