JsonSchema数组验证报错排查:为何'[1,1]'被判定非array类型?
问题:JSON Schema验证报错:'[1,1]' is not of type 'array'
我的代码抛出如下验证错误:
jsonschema.exceptions.ValidationError: '[1,1]' is not of type 'array'
但用在线验证器检查时结果正常,请问哪里操作有误?
我的代码如下:
import json from jsonschema import Draft202012Validator schema = json.loads( """ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "test", "type": "array" } """ ) validator = Draft202012Validator(schema) validator.validate("[1]")
使用版本:jsonschema==4.23.0
错误原因
你传给validator.validate()的是字符串"[1]",而非JSON解析后的数组类型。在线验证器会自动将输入的字符串解析为JSON对象,但你的代码直接传入了未解析的字符串,jsonschema会把它当作字符串类型校验,自然不符合schema中要求的array类型。
修正方案
有两种方式可以解决:
- 将字符串解析为JSON数组后传入:
validator.validate(json.loads("[1]"))
- 直接传入Python原生数组:
validator.validate([1])
内容的提问来源于stack exchange,提问作者user21141188
相关产品推荐
相关产品推荐

