Python for AIPython 3.10+ · Pydantic 2.12
Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
34 small wins to finish your pathNext lesson →

model_validate_json

model_validate_json is a Pydantic method that reads JSON text and builds a checked model from it, raising ValidationError when anything is wrong.

Last updated: 30 Sep, 2026 · Python 3.14 · Pydantic 2.12

try and except caught answers that were not JSON. An answer can also be perfect JSON with the wrong values in it. The Triage model from Pydantic models catches both in one step.

Syntax:

python
result = Model.model_validate_json(json_text)

Checking one answer

Keep tickets.json from JSON in the same folder; the code below reads it.

Examplethe Triage model from the Pydantic models lesson
from typing import Literal
from pydantic import BaseModel, Field

class Triage(BaseModel):
    category: Literal["billing", "shipping", "other"]
    priority: int = Field(ge=1, le=5)
Examplefrom the Stand-in model lesson
import json

def ask_model(ticket_text):
    text = ticket_text.lower()
    if "charged" in text or "refund" in text:
        return '{"category": "billing", "priority": 4}'
    if "parcel" in text or "arrived" in text:
        return '{"category": "shipping", "priority": 3}'
    return "I am not sure how to sort this one."

with open("tickets.json") as f:
    tickets = json.load(f)
Example
answer = ask_model("I was charged twice for one order")
result = Triage.model_validate_json(answer)
print(result)
print(result.category)

model_validate_json takes the answer text, reads it as JSON, and builds a Triage from it, checking every field on the way. It replaces json.loads plus your own checks.

Catching both kinds of wrong answer

Example
from pydantic import ValidationError

for answer in ["I am not sure how to sort this one.", '{"category": "sales", "priority": 9}']:
    try:
        Triage.model_validate_json(answer)
    except ValidationError as error:
        print(error)
        print("---")

The first is not JSON at all, and the error says Invalid JSON. The second is valid JSON that breaks both rules. Either way it is one exception, ValidationError, so one except handles both.

Project files used on this pageThis lesson builds on a project from earlier lessons. The code below imports this file. Click a file to see its code, or follow the link to the lesson that wrote it. To run the code yourself, keep it in the same folder.
View the code here
tickets.json
[
  {
    "id": 1,
    "customer": "Asha",
    "text": "I was charged twice for one order"
  },
  {
    "id": 2,
    "customer": "Ben",
    "text": "My parcel has not arrived"
  },
  {
    "id": 3,
    "customer": "Chen",
    "text": "Can I get a refund for the blue mug?"
  },
  {
    "id": 4,
    "customer": "Dara",
    "text": "How do I change my password?"
  },
  {
    "id": 5,
    "customer": "Eli",
    "text": "The parcel arrived but the box was crushed"
  }
]

Checking every ticket

Example
checked = []
for ticket in tickets:
    try:
        result = Triage.model_validate_json(ask_model(ticket["text"]))
    except ValidationError:
        print(ticket["id"], "needs a person")
        continue
    checked.append(result)
    print(ticket["id"], result.category, result.priority)

print(len(checked), "checked")

Four tickets pass and ticket 4 goes to a person, with no json.loads and no hand-written range check.

Telling the model the shape

Many model APIs accept a JSON Schema, a description of the shape an answer must have, and use it to steer the model. Pydantic writes one from your class:

Example
import json
print(json.dumps(Triage.model_json_schema(), indent=2))

The allowed categories and the 1 to 5 limit are all in there. When a framework says it supports structured output with a Pydantic class, this schema is what it sends.

json.loads vs model_validate_json

json.loadsTriage.model_validate_json
Gives backA dictionaryA Triage object
Not JSONJSONDecodeErrorValidationError
JSON with a bad valueAcceptedValidationError

Where model_validate_json shows up in AI code

  • Right after every model call that was asked for JSON.
  • Reading a JSON file of settings or test cases into typed objects.
Watch out. A model that wraps its JSON in a code fence, ```json ... ```, fails the check as Invalid JSON. Ask for JSON only in the prompt, and treat a failure as a ticket for a person, as the loop above does.
Try it yourself
  • Make ask_model return priority 7 for shipping tickets and run the loop again.
  • Print error.errors() instead of error inside the except.
  • Add "account" to the Literal and a password branch to ask_model.

Little by little, you're building something great.