【发布时间】:2018-02-05 16:52:18
【问题描述】:
我正在尝试使用 Python 3 中的 jsonschema 模块针对模板 JSON 架构递归验证自定义 JSON 架构。
自定义 JSON 如下所示:
{
"endpoint": "rfc",
"filter_by": ["change_ref", "change_i"],
"expression": [
{
"field": "first_name",
"operator": "EQ",
"value": "O'Neil"
},
"AND",
[
{
"field": "last_name",
"operator": "NEQ",
"value": "Smith"
},
"OR",
{
"field": "middle_name",
"operator": "EQ",
"value": "Sam"
}
]
],
"limit_results_to": "2"
}
以上可以通过添加多个ANDs 和ORs 来进一步概括 => 我的问题与递归有关。
我尝试验证此架构的模板位于以下代码段中:
import json
import jsonschema
def get_data(file):
with open(file) as data_file:
return json.load(data_file)
def json_schema_is_valid():
data = get_data("other.json")
valid_schema = {
"type": "object",
"required": ["endpoint", "filter_by", "expression", "limit_results_to"],
"properties": {
"endpoint": {
"type": "string",
"additionalProperties": False
},
"filter_by": {
"type": ["string", "array"],
"additionalProperties": False
},
"limit_results_to": {
"type": "string",
"additionalProperties": False
},
"expression": {
"type": "array",
"properties": {
"field": {
"type": "string",
"additionalProperties": False
},
"operator": {
"type": "string",
"additionalProperties": False
},
"value": {
"type": "string",
"additionalProperties": False
}
},
"required": ["field", "operator", "value"]
}
}
}
return jsonschema.validate(data, valid_schema)
if __name__ == '__main__':
print(json_schema_is_valid())
现在,似乎有些问题,因为当我运行上面的代码时,我得到了None,这可能(不是)没问题。当我试图以不允许的方式修改 property 的 type 时,我没有得到任何异常。我的模板有问题吗? Here,看起来表达式属性没有被解析。此外,我阅读了here,我可以使我的模板使用'$ref': '#' 递归地验证我的自定义 JSON 模式,但我不太了解如何使用它。有人可以给我一些提示吗?
【问题讨论】:
标签: python json python-3.x jsonschema