我想检查JSON字符串是否是有效的Pydantic模式。
from pydantic import BaseModel
class MySchema(BaseModel):
val: int
我只需尝试一下就可以做到这一点:
import json
valid = '{"val": 1}'
invalid = '{"val": "horse"}'
def check_valid(item):
try:
MySchema(**json.loads(item))
return True
except:
return False
print(check_valid(valid))
print(check_valid(invalid))
输出:
True
False
使用try/except来得到一个真/假似乎是不好的做法。有更好的方法吗?
import pydantic
class MySchema(pydantic.BaseModel):
val: int
MySchema.parse_raw('{"val": 1}')
MySchema.parse_raw('{"val": "horse"}')
我认为这将是最简单的解决方案:(
我认为这是一个很好的方法,我只建议将JSON解析与模型实例化分开处理,并在捕获异常时更加具体,如下所示:
import pydantic
import json
class MySchema(pydantic.BaseModel):
val: int
invalid_json = '{"invalid": 123'
invalid_value = '{"val": "horse"}'
invalid_key = '{"wrong_key": 1}'
valid = '{"val": 1}'
valid_2 = '{"val": "1"}'
def check_valid(item):
try:
json_item = json.loads(item)
# Catch potential JSON formatting problems:
except json.JSONDecodeError as exc:
print(f"ERROR: Invalid JSON: {exc.msg}, line {exc.lineno}, column {exc.colno}")
return False
try:
MySchema(**json_item)
# Catch pydantic's validation errors:
except pydantic.ValidationError as exc:
print(f"ERROR: Invalid schema: {exc}")
return False
return True
print(check_valid(invalid_json))
# ERROR: Invalid JSON: Expecting ',' delimiter, line 1, column 16
# False
print(check_valid(invalid_value))
# ERROR: Invalid schema: 1 validation error for MySchema
# val
# value is not a valid integer (type=type_error.integer)
# False
print(check_valid(invalid_key))
# ERROR: Invalid schema: 1 validation error for MySchema
# val
# field required (type=value_error.missing)
# False
print(check_valid(valid))
# True
print(check_valid(valid_2))
# True
当然,您可以将逻辑拆分为两个函数,一个负责JSON验证,另一个负责pydantic
模型。