Python JSON 对象数组的模式验证
Python JSON schema validation for array of objects
我正在尝试使用下面列出的模式验证 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
不是有效关键字,因此将被忽略。唯一发生的验证是在顶层,验证数据是一个对象并且 属性 是一个数组。
我正在尝试使用下面列出的模式验证 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
不是有效关键字,因此将被忽略。唯一发生的验证是在顶层,验证数据是一个对象并且 属性 是一个数组。