Python jsonschema 验证
Python jsonschema validation
在 Python 中,我需要像这样验证复杂的 json 数据结构:
datainstances = {"apache1" :{"user":1,"dirname":"apache1dir","blah":42},"apache2" :{"user":"apache2","dirname":"apache2dir"},"apache3" :{"user1":"apache2","dirname":"apache2dir"}}
所以我使用 json模式验证函数来对抗这个模式
schemainstances = {
"definitions" :{
"instance":{
"type":"object",
"properties": {
"user": {"type":"string"},
"dirname": {"type":"string"},
"blah": {"type":"string"}
},
"required" : ["user","blah"]
}
},
"type":"object",
"patternProperties": {
"^[a-z]+$": {"$ref": "#/definitions/instance"}
}
}
我的目的是它不应该将此 json 结构验证为:
- apache1 的用户属性必须是字符串 a
- apache1 的 blah 属性也必须是字符串
我做错了吗?
是我没看到的
编辑代码
import json
from jsonschema import validate
schemainstances = {
"definitions" :{
"instance":{
"type":"object",
"properties":{
"user": {"type":"string"},
"dirname": {"type":"string"},
"blah": {"type":"string"}
},
"required" : ["user","blah"]
}
},
"type":"object",
"patternProperties":{
"^[a-z]+$": {"$ref": "#/definitions/instance"}
}
}
datainstances = {"apache1" :{"user":1,"dirname":"apache1dir","blah":42},"apache2" :{"user":"apache2","dirname":"apache2dir"},"apache3" :{"user1":"apache2","dirname":"apache2dir"}}
retour = validate(datainstances,schemainstances)
print(retour)
您的 patternProperties
条目包含正则表达式“^[a-z]+$”。关键是"apache1"。此密钥与您的正则表达式不匹配,因为它包含一个数字。因为 patternProperties
不匹配,所以没有对您的数据强制执行任何约束。一切都会验证。也许你想要 "^[a-z0-9]+$" 或 "^[a-z]+[0-9]$" 或 "^[a-z]".
在 Python 中,我需要像这样验证复杂的 json 数据结构:
datainstances = {"apache1" :{"user":1,"dirname":"apache1dir","blah":42},"apache2" :{"user":"apache2","dirname":"apache2dir"},"apache3" :{"user1":"apache2","dirname":"apache2dir"}}
所以我使用 json模式验证函数来对抗这个模式
schemainstances = {
"definitions" :{
"instance":{
"type":"object",
"properties": {
"user": {"type":"string"},
"dirname": {"type":"string"},
"blah": {"type":"string"}
},
"required" : ["user","blah"]
}
},
"type":"object",
"patternProperties": {
"^[a-z]+$": {"$ref": "#/definitions/instance"}
}
}
我的目的是它不应该将此 json 结构验证为:
- apache1 的用户属性必须是字符串 a
- apache1 的 blah 属性也必须是字符串
我做错了吗? 是我没看到的
编辑代码
import json
from jsonschema import validate
schemainstances = {
"definitions" :{
"instance":{
"type":"object",
"properties":{
"user": {"type":"string"},
"dirname": {"type":"string"},
"blah": {"type":"string"}
},
"required" : ["user","blah"]
}
},
"type":"object",
"patternProperties":{
"^[a-z]+$": {"$ref": "#/definitions/instance"}
}
}
datainstances = {"apache1" :{"user":1,"dirname":"apache1dir","blah":42},"apache2" :{"user":"apache2","dirname":"apache2dir"},"apache3" :{"user1":"apache2","dirname":"apache2dir"}}
retour = validate(datainstances,schemainstances)
print(retour)
您的 patternProperties
条目包含正则表达式“^[a-z]+$”。关键是"apache1"。此密钥与您的正则表达式不匹配,因为它包含一个数字。因为 patternProperties
不匹配,所以没有对您的数据强制执行任何约束。一切都会验证。也许你想要 "^[a-z0-9]+$" 或 "^[a-z]+[0-9]$" 或 "^[a-z]".