Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if JSON string is valid Pydantic schema

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?

like image 504
Student Avatar asked Sep 15 '25 16:09

Student


1 Answers

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

like image 153
jacek2v Avatar answered Sep 17 '25 08:09

jacek2v