Full answer
python
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class Signup:
email: str
age: int
plan: str
class ValidationError(Exception):
pass
def parse_signup(text):
try:
data = json.loads(text)
except json.JSONDecodeError as e:
raise ValidationError([f"invalid JSON at line {e.lineno} column {e.colno}"]) from None
errors = []
email = data.get("email")
if not isinstance(email, str) or "@" not in email:
errors.append("email must contain @")
age = data.get("age")
if not isinstance(age, int) or isinstance(age, bool) or not 13 <= age <= 120:
errors.append("age must be an integer from 13 to 120")
if data.get("plan") not in {"free", "pro"}:
errors.append("plan must be free or pro")
if errors:
raise ValidationError(errors)
return Signup(email, age, data["plan"])
print(parse_signup('{"email": "a@x.in", "age": 21, "plan": "pro"}'))
for bad in ['{"email": "ax.in", "age": true, "plan": "gold"}', '{"email": ']:
try:
parse_signup(bad)
except ValidationError as e:
print(e.args[0])Output:
text
Signup(email='a@x.in', age=21, plan='pro')
['email must contain @', 'age must be an integer from 13 to 120', 'plan must be free or pro']
['invalid JSON at line 1 column 11']The valid input becomes a frozen dataclass. The second input has three problems, all reported together, which is friendlier for form users than fixing them one at a time. true is rejected as an age because bool is a subclass of int in Python, a subtle case worth checking. Malformed JSON produces a position-specific message, and from None hides the internal traceback chain.
python
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class Signup:
email: str
age: int
plan: str
class ValidationError(Exception):
pass
def parse_signup(text):
try:
data = json.loads(text)
except json.JSONDecodeError as e:
raise ValidationError([f"invalid JSON at line {e.lineno} column {e.colno}"]) from None
errors = []
email = data.get("email")
if not isinstance(email, str) or "@" not in email:
errors.append("email must contain @")
age = data.get("age")
if not isinstance(age, int) or isinstance(age, bool) or not 13 <= age <= 120:
errors.append("age must be an integer from 13 to 120")
if data.get("plan") not in {"free", "pro"}:
errors.append("plan must be free or pro")
if errors:
raise ValidationError(errors)
return Signup(email, age, data["plan"])
print(parse_signup('{"email": "a@x.in", "age": 21, "plan": "pro"}'))
for bad in ['{"email": "ax.in", "age": true, "plan": "gold"}', '{"email": ']:
try:
parse_signup(bad)
except ValidationError as e:
print(e.args[0])Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Parse, then validate explicitly
- Collect all errors
- bool is a subclass of int
- Return typed objects
- pydantic automates this
Common mistakes
- Stopping at the first error
- Accepting True as an integer
Follow-ups
- How would pydantic express this model?
- How should validation errors map to HTTP responses?
Tips
- Catch the bool case