首页 > 解决方案 > 对象数组的 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

标签: pythonjsonjsonschema

解决方案


在:"npcs": { "$ref": "#/definitions/NpcEntry" }

将“NPC”更改为“项目”。npcs不是有效的关键字,因此被忽略。唯一发生的验证是在顶层,验证数据是一个对象并且一个属性是一个数组。


推荐阅读