简体   繁体   English

检查 JSON 字符串是否有效 Pydantic 模式

[英]Check if JSON string is valid Pydantic schema

I want to check if a JSON string is a valid Pydantic schema.我想检查 JSON 字符串是否是有效的 Pydantic 模式。

from pydantic import BaseModel

class MySchema(BaseModel):
    val: int

I can do this very simply with a try/except:我可以通过 try/except 非常简单地做到这一点:

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))

Output: Output:

True
False

Use of try/except to get a true/false seems like bad practice.使用 try/except 来获得真/假似乎是不好的做法。 Is there a better way?有没有更好的办法?

I think it's a good approach, I would only suggest treating the JSON parsing separately from the model instantiation, and being more specific when catching the exceptions, see below:我认为这是一个很好的方法,我只建议将 JSON 解析与 model 实例化分开处理,并且在捕获异常时更具体,见下文:

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

Of course, you could split up the logic into two functions, one taking care of the JSON validation, and the other of the pydantic model.当然,您可以将逻辑拆分为两个函数,一个负责 JSON 验证,另一个负责pydantic model。

import pydantic

class MySchema(pydantic.BaseModel):
    val: int

MySchema.parse_raw('{"val": 1}')
MySchema.parse_raw('{"val": "horse"}')

I think it will be the simplest solution:)我认为这将是最简单的解决方案:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM