Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.4 — Describing the Shape with JSON Schema
LLM Engineering · Example 1 of 2

Build a JSON Schema from a list of fields

The schema is built as plain data, then printed in compact form. Java uses the course's Json helper.

JSON Schema is a standard way to write down the shape of JSON: which keys exist, which are required, what type each has, and which values are allowed. The same schema can steer the model, drive a provider's constrained decoding and check the reply.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write the schema (as a Python dictionary) for an object with a required string city and a required integer days, rejecting any other keys. Print it with json.dumps, compact.

02

Write required_names(schema) that returns the list of required keys of an object schema, or an empty list if there are none.

Explain it without notes

01

What are the main parts of a JSON Schema for an object?

02

What is the difference between a field that is optional and a field that is nullable?

03

Why are enums important for LLM output?

04

Why generate schemas from types instead of writing them by hand?

Build a JSON Schema from a list of fields
Sign in to run this example in your browser.

Expected output

{"type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer"},"plan":{"type":"string","enum":["free","pro","team"]},"note":{"type":"string"}},"required":["name","age","plan"],"additionalProperties":false}
required: name, age, plan