【问题标题】:Python JSON schema validation for array of objects对象数组的 Python JSON 模式验证
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢你,我的代码盲更严重了。
  • 我们都去过那里:)
猜你喜欢
  • 1970-01-01
  • 2020-07-28
  • 2018-09-20
  • 2017-10-23
  • 2015-10-24
  • 1970-01-01
  • 2018-02-23
  • 2021-05-18
  • 2020-03-29
相关资源
最近更新 更多