Force an LLM to return JSON in JavaScript
- Authors
- Name
- Hamza Rahman
- Published on
- -2 mins read
The safest way to get JSON from an LLM is to use a schema-based response format.
This example asks the model to classify a support message and return only the fields your app needs.
Install
npm install openai zodSet your API key:
export OPENAI_API_KEY="your_api_key_here"Code
import OpenAI from 'openai'import { zodTextFormat } from 'openai/helpers/zod'import { z } from 'zod'
const openai = new OpenAI()
const TicketLabel = z.object({ category: z.enum(['billing', 'bug', 'feature_request', 'other']), priority: z.enum(['low', 'medium', 'high']), summary: z.string(),})
const response = await openai.responses.parse({ model: 'gpt-5.5', input: [ { role: 'system', content: 'Classify the support ticket. Keep the summary under 20 words.', }, { role: 'user', content: 'My invoice was charged twice this month. Please fix it quickly.', }, ], text: { format: zodTextFormat(TicketLabel, 'ticket_label'), },})
const ticket = response.output_parsed
console.log(ticket.category)console.log(ticket.priority)console.log(ticket.summary)Example output:
{ category: 'billing', priority: 'high', summary: 'Customer was charged twice and needs billing correction.'}Why not just JSON.parse?
You can ask a model to "return JSON", but plain prompting can still produce invalid JSON, extra text, or missing fields.
Schema-based output is better when the result goes into real application code.
Use it for:
- Ticket classification
- Lead enrichment
- Entity extraction
- Moderation labels
- App-ready LLM responses
References
Related articles
OpenAI function calling JavaScript example
Minimal OpenAI function calling example in JavaScript using a local tool and the Responses API.
OpenAI structured outputs with Zod in JavaScript
Use OpenAI structured outputs with a Zod schema to get typed JSON back from an LLM in JavaScript.
LangChain JS agent with a custom tool
Create a small LangChain JavaScript agent with one custom tool using createAgent, tool, and Zod.

