jsonschema脚本测试

该博客主要展示了如何使用 `jsonschema` 库进行 JSON 数据验证,并处理验证过程中遇到的 SchemaError 和 ValidationError。首先定义了一个 JSON Schema,用于验证融资信息数据结构,然后尝试验证一个包含错误的数据实例。当验证失败时,博客详细地打印出错误字段、原因及相关信息。此外,还提供了一个简化版的验证过程,直接输出验证结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import jsonschema
from jsonschema import validate, draft7_format_checker
from jsonschema.exceptions import SchemaError, ValidationError
schema = {
    "title": "validate_融资信息数据结构",
    "description": "validate_融资信息数据结构",
    "type": "object",
    "properties": {
        "one": {
            "type": "string",
            "maxLength": 70,
            "minLength": 2,
            "not": {
                "enum":["\\N"]
            }
        }
    }
}

data = {
    'one':123,
    'two': '',
    'three': '',
    "companyNameEngD7esc":""
}



results = {}
try:
    a = validate(instance=data, schema=schema, format_checker=draft7_format_checker)
    print(a)
except SchemaError as e:
    err_arr = 'site:%s' % "--> ".join([i for i in e.path])
    err_info = 'info:%s' % e.message
    results['schema'] = [err_arr, err_info]
    hint = "False&%s" % results
    print(hint)
except ValidationError as e:
    validator = jsonschema.Draft6Validator(schema)
    errors = validator.iter_errors(data)  # jsondata验证
    for error in errors:
        key = str(error).split('On instance')[1].replace('\n', '').split('\']')[0].replace('[\'', '')
        value = str(error).split('\n')[0]
        results[key] = value
    hint = "False&%s" % results
    print(hint,type(hint))

第二个版本

from jsonschema import validate, ValidationError

schema = {
    "title": "validate_融资信息数据结构",
    "description": "validate_融资信息数据结构",
    "type": "object",
    "properties": {
        "one": {
            "type": "string",
            "maxLength": 70,
            "minLength": 2,
            "not": {
                "enum":["\\N"]
            }
        }
    }
}

data = {
    'one':123,
    'two': '',
    'three': '',
    "companyNameEngD7esc":""
}


try:
    validate(instance=data, schema=schema)
    print("检验通过")
except ValidationError as e:
    print("校验失败")
    for error in e.absolute_schema_path:
        print(f"Field: {error} - Reason: {e.message}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值