python - 对象数组的 Python JSON 模式验证
问题描述
我正在尝试使用下面列出的架构验证 JSON 文件,我可以输入任何其他字段,我不明白,我做错了什么,为什么?
示例 JSON 数据
{
"npcs":
[
{
"id": 0,
"name": "Pilot Alpha",
"isNPC": true,
"race": "1e",
"testNotValid": false
},
{
"id": 1,
"name": "Pilot Beta",
"isNPC": true,
"race": 1
}
]
}
JSON 模式
我已经设置了“required”和“additionalProperties”,所以我认为验证会失败......
FileSchema = {
"definitions":
{
"NpcEntry":
{
"properties":
{
"id": { "type": "integer" },
"name": { "type" : "string" },
"isNPC": { "type": "boolean" },
"race": { "type" : "integer" }
},
"required": [ "id", "name", "isNPC", "race" ],
"additionalProperties": False
}
},
"type": "object",
"required": [ "npcs" ],
"additionalProperties": False,
"properties":
{
"npcs":
{
"type": "array",
"npcs": { "$ref": "#/definitions/NpcEntry" }
}
}
}
JSON 文件和模式是使用 Python 的 jsonschema 包处理的(我在 Mac 上使用 python 3.7)。
我用来读取和验证的方法如下,我删除了很多常规验证,以使代码尽可能短且可用:
import json
import jsonschema
def _ReadJsonfile(self, filename, schemaSystem, fileType):
with open(filename) as fileHandle:
fileContents = fileHandle.read()
jsonData = json.loads(fileContents)
try:
jsonschema.validate(instance=jsonData, schema=schemaSystem)
except jsonschema.exceptions.ValidationError as ex:
print(f"JSON schema validation failed for file '{filename}'")
return None
return jsonData
解决方案
在:"npcs": { "$ref": "#/definitions/NpcEntry" }
将“NPC”更改为“项目”。npcs
不是有效的关键字,因此被忽略。唯一发生的验证是在顶层,验证数据是一个对象并且一个属性是一个数组。
推荐阅读
- javascript - JavaScript:模态形式fadeInDown
- c - 执行 foo(x, &x) 之类的操作是否安全?
- regex - 如何将要匹配的表达式分组为一个?
- laravel - 为什么有时 Laravel API 在获取 Vue.js 时返回 404 错误
- html - knockoutjs if 语句并用 html 替换文本
- pandas - str.contains 在 pandas 列中搜索以逗号分隔的多个字符串
- spring-boot - 使用本机查询在 JPA 中进行内部联接
- python - 视图中出现多个错误,编辑模型列表
- java - 无 arg 的 repaint() 是否比带 args 的 repaint() 更好?
- ruby-on-rails - 如何通过 Rails 中的审计协会模型创建正确的 has_one: :