Skip to main content
In this lesson we generate LLM output and reliably transform it into JSON using an output parser. You’ll learn how to:
  • Call a language model to list countries and capitals.
  • Instruct the model to return valid JSON using a JsonOutputParser’s format instructions.
  • Parse the LLM response into native Python data structures for direct use in application logic.
Quick links and references:

1) Imports and a simple LLM call

Start by importing the necessary components and creating an LLM client:
Construct a straightforward prompt template and call the model to get an unconstrained textual answer (a plain list):
Example typical output:
This output is human-readable but not structured. To work with it programmatically, we need to guide the model to emit JSON.

2) Add a JsonOutputParser and obtain format instructions

Instantiate a JsonOutputParser to provide the LLM with exact format instructions. The parser exposes a helper string you can embed in your prompt to ask for valid JSON:
The printed format_instructions will be a short guideline such as “Return a JSON object.” Use this text so the model knows to produce valid, parseable JSON.

3) Create a prompt that includes the format instructions

Embed the parser’s instructions into your prompt using partial_variables. This ensures every invocation contains the necessary instructions for structured output:
Inspect the prompt to confirm the instructions are included:
Example rendered prompt:

4) Invoke the LLM with the structured prompt and parse the result

Call the model with the new prompt and then parse the returned JSON string into native Python types:
Example model output (valid JSON):
Now parse the JSON string into Python:
Example console output:

5) Why this approach helps

  • The parser’s format instructions encourage the LLM to produce valid JSON (or another predictable format), reducing parsing errors.
  • Passing the LLM response through JsonOutputParser converts a string into native Python types (dict, list), which eliminates manual parsing and validation plumbing.
  • Once parsed, the result can be fed directly into application logic, converted into dataclasses, or serialized for storage/transmission.

Quick reference: workflow steps

Always include the parser’s format instructions in the prompt when you want structured output; otherwise the model may return freeform text that fails to parse.

Watch Video