I want to check if a JSON string is a valid Pydantic schema.
from pydantic import BaseModel
class MySchema(BaseModel):
    val: int
I can do this very simply with a 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:
True
False
Use of try/except to get a true/false seems like bad practice. Is there a better way?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With