Issue
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?
Solution
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 :)
Answered By - jacek2v
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.