【发布时间】:2020-10-31 14:59:09
【问题描述】:
我正在尝试使用下面列出的架构验证 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" }
}
}
}
使用 Python 的 jsonschema 包处理 JSON 文件和架构,(我在 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
【问题讨论】:
-
您的问题是什么?你没提吗?
-
问题是:为什么它不起作用,为什么?
-
问题是:为什么它不起作用,为什么? 这很宽泛/含糊。有没有调试过?
-
@AMC 我真的不知道你是如何“调试”它的?我已经扫描了json-schema.org。我希望这是一些语法或我不理解/不理解的东西
-
@PaulMorriss 我真的不知道你是如何“调试”它的?我的意思是调试程序。我建议阅读ericlippert.com/2014/03/05/how-to-debug-small-programs。
标签: python json jsonschema