TypeScript SDK

Structured outputs

Pass a JSON Schema in text.format and call response.toJson() to parse the completed text output. See the Structured Outputs guide for schema rules and supported keywords. Examples use the client created in the quickstart.

TypeScript

const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'Give me a city to visit in Japan.',
  text: {
    format: {
      type: 'json_schema',
      name: 'travel_suggestion',
      schema: {
        type: 'object',
        properties: {
          city: { type: 'string' },
          reason: { type: 'string' },
        },
        required: ['city', 'reason'],
        additionalProperties: false,
      },
    },
  },
});

const suggestion = response.toJson();
console.log(suggestion);

Without a schema argument, toJson() returns unknown. Validate the result before using it at a trust boundary. The non-throwing response.parsed getter returns null when output is incomplete or is not valid JSON.

To validate and infer the TypeScript output type in one step, pass a Standard Schema validator to toJson(schema). It returns the schema's output with any coercions and defaults applied, or throws an error listing each validation issue and path. Supported validators include:

toJson() runs synchronously, so async-only validators (such as Yup) and schemas with async refinements are not supported.

TypeScript

import { z } from 'zod';

const TravelSuggestion = z.object({ city: z.string(), reason: z.string() });

const { city, reason } = response.toJson(TravelSuggestion);

Streaming structured output

When streaming a request with a JSON Schema in text.format, the 'json' event receives the parsed value so far as each text delta arrives. Unfinished strings, arrays, and objects are closed automatically so you can render incremental progress:

TypeScript

{ title: 'Why the' }
{ title: 'Why the sky is blue', lines: [{ speaker: 'host', text: 'Wel' }] }
{ title: 'Why the sky is blue', lines: [{ speaker: 'host', text: 'Welcome back! Today a simple question.' }, { speaker: 'gu' }] }
{ title: 'Why the sky is blue', lines: [{ speaker: 'host', text: 'Welcome back! Today a simple question.' }, { speaker: 'guest', text: 'Why is the sky blue?' }] }

Strings can stop mid-word, including enum values such as 'gu' on the way to 'guest'. Numbers are omitted until complete, so you never see 1 for what becomes 12. In an array, every item before the last element is finished, so you can process each completed item as soon as the next one begins:

TypeScript

const stream = await client.responses.create({
  model: 'grok-4.7',
  input: 'Write a short two-person podcast script about why the sky is blue.',
  reasoning: { effort: 'low' },
  text: {
    format: {
      type: 'json_schema',
      name: 'podcast_script',
      schema: {
        type: 'object',
        properties: {
          title: { type: 'string' },
          lines: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                speaker: { type: 'string', enum: ['host', 'guest'] },
                text: { type: 'string' },
              },
              required: ['speaker', 'text'],
              additionalProperties: false,
            },
          },
        },
        required: ['title', 'lines'],
        additionalProperties: false,
      },
    },
  },
  stream: true,
});

type Line = { speaker: string; text: string };
const print = (line: Line) => console.log(`${line.speaker}: ${line.text}`);
let finished = 0;

const response = await stream
  .on('json', partial => {
    const lines = (partial as { lines?: Array<Line> }).lines ?? [];
    while (finished < lines.length - 1) print(lines[finished++]!);
  })
  .done();

const script = response.toJson() as { title: string; lines: Array<Line> };
for (const line of script.lines.slice(finished)) print(line);

Values from the 'json' event are not validated against your schema. Always read and validate the final result from response.toJson().

The 'json' event uses parsePartialJson(), which is also exported directly. It parses truncated JSON by closing open strings, arrays, and objects, and returns undefined when the text holds no value yet or contains a syntax error:

TypeScript

import { parsePartialJson } from '@grok/sdk';

parsePartialJson('{"title":"Why the'); // { title: "Why the" }
parsePartialJson('{"title":"Why the sky is blue","minutes":1'); // { title: "Why the sky is blue" }
parsePartialJson('{"title":"Why the sky is blue","minutes":12}'); // { title: "Why the sky is blue", minutes: 12 }
parsePartialJson('{"title" "oops"}'); // undefined

Call parsePartialJson() when iterating events in a for await loop or parsing forwarded deltas:

TypeScript

let text = '';
for await (const event of stream) {
  if (event.type === 'response.output_text.delta') {
    text += event.delta;
    console.log(parsePartialJson(text));
  }
}

Last updated: December 1, 2026