为了账号安全,请及时绑定邮箱和手机立即绑定

为 JSON 模式验证组织 Pythonic 字典

为 JSON 模式验证组织 Pythonic 字典

侃侃无极 2021-12-09 18:16:32
场景:我正在尝试在 python 中创建一个 JSON 模式验证器。在这种情况下,我正在构建一个字典,其中包含将用于验证的信息。代码:import jsonimport osfrom pprint import pprintfrom jsonschema import validatefrom jsonschema import Draft4Validatorconfig_dir = r"D:\PROJECTS\etc"config_file = r"schema.json"schema = dict()schema["$schema"] = "https://json-schema.org/schema#"schema["title"] = "Index Schema"schema["description"] = "Schema to describe calendar"schema["type"] = "object"# corecore = dict()core["type"] = "object"core["description"] = "Core settings for calendar"core["frequency"] = {"type": "string",                     "description": "Base frequency ",                     "enum": ["monthly", "daily", "weekly"]}  #problem1core["mark"] = {                "type": "string",                "description": "Mask defining the months",                "if": {"core": {"frequency": {"enum": "monthly"}}}, #problem2                "then": {                         "pattern": "[01]{12}",                         "minLength": 12,                         "maxLength": 12                         }                }core["ref_day"] = {"type": "string",                   "description": "First day"                   }core["objective1"] = {"type": "object",                     "description": "Information Calendar",                     "properties": {"day": "string",                                    "holiday": "string",                                    "relative": {"unit": ["D", "M", ""],                                                        "offset": "number"                                                        }                                    }                    }问题:在这里我遇到了 3 个问题: 问题 1:是否可以创建一个列表,其中要验证的 JSON 中的值必须在此列表中,否则会失败?问题 2:是否可以使用我在此代码段中编写的 if 函数?问题3:为了减少出错的可能性,是否可以通过以下方式创建字典?主要问题:当我运行第一段代码时,我创建了字典并且整个过程都没有出现错误,但是当我打印结果时,我得到一个none,据我所知,这表明有问题。我在这里做错了什么?
查看完整描述

1 回答

?
达令说

TA贡献1821条经验 获得超6个赞

Draft4Validator.check_schema并不意味着返回任何东西。(换句话说,它返回None.)


check_schema如果出现问题则引发异常;如果没有,它会运行到完成。


您可以在以下代码中看到这一点check_schema:


    @classmethod

    def check_schema(cls, schema):

        for error in cls(cls.META_SCHEMA).iter_errors(schema):

            raise exceptions.SchemaError.create_from(error)

所以,这种行为是正确的。


查看完整回答
反对 回复 2021-12-09
  • 1 回答
  • 0 关注
  • 207 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号