Intermediate12 min read

Get structured JSON from a model

Extract fields into a predictable shape and validate the result before your app uses it.

Design the output shape

Use the local Python example as a starting point. Say an app needs a task title and a due date. Make both keys required. Allow null for a missing date. Tell the model the same rules in the prompt.

Start a new file named extract_task.py in the same directory as local_chat.py. Paste in this block.

import json
from local_chat import chat

schema = {
    "type": "object",
    "properties": {
        "task": {"type": "string"},
        "due_date": {"type": ["string", "null"]},
    },
    "required": ["task", "due_date"],
    "additionalProperties": False,
}
payload = {
    "model": "qwen2.5:1.5b",
    "messages": [{
        "role": "user",
        "content": (
            "Extract task and due_date from this note: Leah will email the draft. "
            "Use null when the note does not state a due date."
        ),
    }],
    "format": schema,
    "options": {"temperature": 0},
    "stream": False,
}

Validate what you receive

The HTTP response is JSON. Its message.content field contains the model’s JSON as a string, so parse that separately. Append this block to extract_task.py and run the file.

result = chat(payload)
try:
    item = json.loads(result["message"]["content"])
except (KeyError, TypeError, json.JSONDecodeError):
    raise SystemExit("The model did not return a usable object.") from None

if (
    not isinstance(item, dict)
    or set(item) != {"task", "due_date"}
    or not isinstance(item["task"], str)
    or not item["task"].strip()
    or (item["due_date"] is not None and not isinstance(item["due_date"], str))
):
    raise SystemExit("The result does not match the expected fields.")

print(item)

Try it with missing and explicit dates

Run the script with the original note. Expect a task describing the draft email and a null due date. Add “by Friday” to the note and compare. If the app requires an ISO calendar date, define how to handle relative dates and enforce that rule in your app.

What to check

A schema constrains the output’s shape. Compare the values against the original note to catch invented or misplaced dates.

Check your understanding

Can a correctly shaped JSON object contain the wrong due date?

Yes. Type validation checks the structure. A separate check must verify that the date is supported by the input.

Sources

Search the guide