What is JsonOutputParser?
JsonOutputParser sits at the end of a LangChain LCEL chain and turns the model's text output into a Python dict or list. It handles two common LLM response patterns: raw JSON ({"key": "value"}) and JSON wrapped in a markdown code fence (```json ... ```). Both are detected and stripped automatically, which matters because most models default to the fenced form when instructed to "respond with JSON".
Passing a Pydantic model class via pydantic_object serves two roles: it generates format instructions you can inject into the prompt via parser.get_format_instructions(), and it validates the parsed output against the schema, raising OutputParserException on mismatch. Without a schema, the parser returns whatever the model produces — useful for flexible/dynamic shapes but leaves validation to your code.
For production workloads where you need guaranteed schema compliance, prefer model.with_structured_output(MySchema) instead. That API uses the provider's native tool-calling or JSON-mode endpoint, which is enforced at the model level rather than post-processing. JsonOutputParser is the right choice when you're working with weaker models that lack native JSON mode, or when you want to stream partial JSON chunks as they arrive.
When to Use
You need structured data from the model. Use JsonOutputParser to extract and validate JSON.
Use Cases
- • Parse structured responses
- • Data extraction
- • API responses
- • Form filling
- • Schema validation
- • Structured data
Key Features
- ✓ JSON parsing
- ✓ Markdown handling
- ✓ Validation
- ✓ Works with all models
- ✓ Dict/list output
- ✓ Error messages
When NOT to Use
For guaranteed structured output—use .with_structured_output() instead.
Notes
get_format_instructions() tells the model the exact output shape
Inject parser.get_format_instructions() into your prompt template via partial_variables. This generates a schema description the model uses to format its response. Without it, you are relying on the model's general "respond with JSON" instruction, which is far less reliable — especially for nested schemas.
OutputParserException on malformed JSON
When the model returns invalid JSON (truncated, escaped incorrectly, trailing commas), JsonOutputParser raises OutputParserException. Wrap your chain call in a try/except and either retry with a clarification prompt or fall back to a default value. The exception message includes the raw output for debugging.
Prefer with_structured_output for GPT-4o and Claude
Modern providers support native JSON mode or tool calling. model.with_structured_output(MySchema) enforces the schema at the API level — the model cannot produce syntactically invalid JSON. Use JsonOutputParser only when your model does not support native structured output (e.g. older OSS models, local Ollama).
Streaming yields accumulated partial objects
When streaming through JsonOutputParser, each chunk is an incrementally-complete dict, not a delta. The first chunks may be empty {} while the model generates the opening brace. This is by design — the parser accumulates tokens and tries to parse at each step.
Import
from langchain_core.output_parsers import JsonOutputParser
Configuration
| Parameter | Type | Default | Purpose |
|---|---|---|---|
| pydantic_object | Type | None | Optional Pydantic model for validation |
Usage Examples
Basic JSON Parsing
parser = JsonOutputParser()
chain = prompt | model | parser
result = chain.invoke({'input': 'data'})
print(result) # Python dict
Pydantic Schema + Format Instructions
from langchain_core.output_parsers import JsonOutputParser
from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float
in_stock: bool
parser = JsonOutputParser(pydantic_object=Product)
prompt = PromptTemplate(
template="Extract product info.\n{format_instructions}\n{query}",
partial_variables={"format_instructions": parser.get_format_instructions()},
)
chain = prompt | model | parser
result = chain.invoke({"query": "iPhone 15, $999, available"})
Streaming Partial JSON
# Stream partial JSON as it arrives
parser = JsonOutputParser()
chain = prompt | model | parser
for chunk in chain.stream({"input": "list 3 colors"}):
print(chunk) # partial dicts accumulate
Common Pitfalls
❌ Rely on model to output valid JSON without guidance
✅ Use .with_structured_output() for guaranteed format
Related LangChain References
Browse the full LangChain API reference index to explore more classes, methods, and decorators, or start with the LangChain introduction tutorial for end-to-end context on building with JsonOutputParser and the wider framework.
JsonOutputParser FAQ
What is JsonOutputParser in LangChain?
Parse JSON from model output. JsonOutputParser sits at the end of a LangChain LCEL chain and turns the model's text output into a Python dict or list. It handles two common LLM response patterns: raw JSON ({"key": "value"}) and JSON wrapped in a markdown code fence (```json ... ```). Both are detected and stripped automatically, which matters because most models default to the fenced form when instructed to "respond with JSON". Passing a Pydantic model class via pydantic_object serves two roles: it gener…
Which package provides JsonOutputParser?
DevShelfHub documents JsonOutputParser from the langchain-core package. Pin your installed LangChain version and match imports to the snippet on this page.
When should I use JsonOutputParser?
You need structured data from the model. Use JsonOutputParser to extract and validate JSON.
When should I avoid using JsonOutputParser?
For guaranteed structured output—use .with_structured_output() instead.
How do I import JsonOutputParser in Python?
from langchain_core.output_parsers import JsonOutputParser
Where can I explore more LangChain API reference pages?
Open the LangChain API reference index on DevShelfHub to browse classes, methods, and decorators, each with runnable examples, parameters, common mistakes, and cross-links.