我正在尝试使用下面列出的模式来验证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" }
将“ npcs”更改为“ items”。npcs
不是有效的关键字,因此将被忽略。唯一发生的验证是在顶层,验证数据是对象,并且一个属性是数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句