TokenHot
HomeModelsConsoleDocumentationBlog
✓ English简体中文Translation unavailable繁體中文Translation unavailable日本語Translation unavailableFrançaisTranslation unavailableРусскийTranslation unavailableTiếng ViệtTranslation unavailable
TokenHot

One API. A model catalog. Usage-based billing.

Product

  • Models
  • Pricing
  • How It Works
  • Integration guides
  • About

Popular Models

  • gemini-4-neon
  • gpt-6.2-astra
  • claude-fable-5-2
  • Kimi K3.1 Pro
  • DeepSeek V4.1 Flash
  • qwen3.8-flash
  • doubao-seedream-5-5
  • wan3.0-video-prime

Model Providers

  • OpenAI
  • Anthropic
  • Google
  • DeepSeek
  • Qwen
  • ByteDance
  • Doubao
  • MiniMax
  • Z.ai (GLM)
  • xAI
  • Moonshot AI
  • Xiaomi MiMo
  • Kling

Resources

  • Docs
  • Blog
  • hi@tokenhot.ai
  • LLMs.txt

Trust & Support

  • Trust Center
  • Security & Data
  • Support
  • Privacy
  • Terms
  • Refund Policy
© 2026 NEXORA AI PTE. LTD. · Tokenhot
TokenHot
  1. Home
  2. Blog
  3. API & Integrations
  4. JSON Mode vs Structured Outputs: How to Get Reliable LLM Data
API & Integrations

JSON Mode vs Structured Outputs: How to Get Reliable LLM Data

Choose JSON mode or strict Structured Outputs, then validate one order through parsing, schema checks, and business rules before accepting LLM data.

Tokenhot Team
November 30, 202610 min read
JSON Mode vs Structured Outputs: How to Get Reliable LLM Data
Share𝕏

Use Structured Outputs when your chosen model and endpoint support a strict schema. Use JSON mode when you need parseable JSON and can validate its shape yourself. In either case, check that the response completed successfully, then validate the data against the source and your application rules before accepting it.

Valid JSON can contain a wrong order total. A perfectly shaped object can belong to the wrong order. Formatting is one part of the contract.

This guide follows one illustrative order through three checks: JSON syntax, schema conformance, and business validation. The goal is to produce a validated candidate for your application, not to let model output authorize a purchase.

What each output mode actually gives you

OpenAI's Structured Outputs guide distinguishes JSON mode from strict schema output. Its guarantees apply to supported models, API surfaces, and schema features; refusals and incomplete responses require separate handling.

Approach What it targets What your application still checks
Prompt asking for JSON A formatting instruction Completion, parsing, shape, and business rules
JSON mode Valid JSON, with documented edge cases Completion, shape, and business rules
Strict Structured Outputs Adherence to a supported schema Completion, refusal, factual values, and business rules

For JSON mode, explicitly instruct the model to return JSON. For schema output, check the supported schema subset before submitting the request. A full JSON Schema document accepted by your local validator is not automatically a supported generation schema.

If the model must call a tool, use the API's tool/function-calling contract and validate arguments before execution. The order extraction below is a response-format task, so it needs no tool call.

Use the same order for all three checks

Suppose the source text is:

Order ORD-1042: two notebooks at USD 19.99 each. Order total: USD 39.98.

The desired candidate is:

{
  "order_id": "ORD-1042",
  "currency": "USD",
  "quantity": 2,
  "unit_price_cents": 1999,
  "total_cents": 3998
}

This example uses integer cents for USD and EUR. A production multi-currency system needs currency-specific minor-unit rules; do not assume every currency has two decimal places.

Check 1: Can you parse it?

The object above is valid JSON. This version is not:

{"order_id":"ORD-1042","currency":"USD","quantity":2,"unit_price_cents":1999,"total_cents":3998,}

The trailing comma makes it invalid. Markdown fences or prose around an otherwise valid object also prevent the entire content string from being parsed as JSON. Parse the complete returned text; avoid silently cutting out a substring that happens to look like an object.

Now change quantity to the string "2". The result still parses. Parsing alone has not protected the types your order handler expects.

Check 2: Does it match the schema?

Use this small generation schema for the same order:

{
  "type": "object",
  "properties": {
    "order_id": {"type": "string"},
    "currency": {"type": "string", "enum": ["USD", "EUR"]},
    "quantity": {"type": "integer"},
    "unit_price_cents": {"type": "integer"},
    "total_cents": {"type": "integer"}
  },
  "required": ["order_id", "currency", "quantity", "unit_price_cents", "total_cents"],
  "additionalProperties": false
}

The JSON Schema object reference explains required and additionalProperties. Here, all five keys must be present, and extra keys are forbidden. An integer field cannot be replaced with a numeric string. OpenAI's strict output contract also requires object schemas to disallow additional properties and requires fields to be declared required.

The schema deliberately leaves positive quantities, safe arithmetic, and the relationship between fields to the application. That keeps the difference visible: an order with total_cents: 4998 satisfies this schema even though two notebooks at 1999 cents do not total 4998 cents.

Check 3: Is it the correct order?

For this extraction job, check that:

  • The order ID and currency match the trusted job context.
  • Quantity is positive; monetary values are nonnegative safe integers.
  • Quantity × unit price is safe to represent and equals the total.
  • Extracted values agree with the source document. For a real checkout, prices and totals must also be checked against authoritative catalog, tax, discount, and shipping rules.

The simple multiplication rule applies to this example's single line with no tax, discount, or shipping. Do not impose it unchanged on an invoice with additional charges.

An internally consistent extraction can still misread the source. Two items at 2499 cents, totaling 4998 cents, would pass arithmetic but contradict the text. Schema conformance and arithmetic do not establish truth.

Put the schema in the correct request field

The following JavaScript builds request objects locally. Set orderSchema to the parsed schema above. modelId is the exact model ID you have independently selected for the endpoint; it is not a universal alias.

function buildOrderRequests(modelId, orderSchema) {
  const instruction = "Extract this single order as JSON. Copy values from the source; " +
    "use integer cents for money. If information is missing, do not invent it.";
  const source = "Order ORD-1042: two notebooks at USD 19.99 each. Order total: USD 39.98.";
  return {
    chat: {
      model: modelId,
      messages: [
        {role: "system", content: instruction},
        {role: "user", content: source}
      ],
      response_format: {
        type: "json_schema",
        json_schema: {name: "order", strict: true, schema: orderSchema}
      }
    },
    responses: {
      model: modelId,
      instructions: instruction,
      input: source,
      text: {format: {type: "json_schema", name: "order", strict: true, schema: orderSchema}}
    }
  };
}

Chat Completions uses response_format; Responses uses text.format. These are different request objects, not two fields to send together. See the official Chat Completions request reference and Responses request reference.

For JSON mode, replace the Chat object's entire response_format with {type: "json_object"}, or the Responses object's text.format with {type: "json_object"}. Keep the explicit JSON instruction and run the same local validation.

This required-field schema is for a source with complete information. For incomplete documents, design an explicit missing-data contract—for example, supported nullable fields with a manual-review outcome—and update the local validator accordingly. A prompt saying “do not invent” cannot make a required integer represent an unknown value.

Validate a completed response before using the object

This local JavaScript example accepts one non-streaming Chat Completions response. It implements the exact shape above by hand, then applies this order's business rules. It is not a general JSON Schema validator.

function validateOrder(reply, expected) {
  if (!Array.isArray(reply?.choices) || reply.choices.length !== 1) {
    throw Error("envelope: expected one choice");
  }
  const choice = reply.choices[0];
  const message = choice?.message;
  if (message?.refusal) throw Error("refusal");
  if (choice?.finish_reason !== "stop") throw Error("completion: not final");
  if (message?.role !== "assistant" || message.tool_calls?.length || message.function_call) {
    throw Error("envelope: expected assistant text only");
  }
  if (typeof message.content !== "string") throw Error("content: missing text");

  let order;
  try { order = JSON.parse(message.content); }
  catch { throw Error("syntax: invalid JSON"); }
  if (order === null || typeof order !== "object" || Array.isArray(order)) {
    throw Error("schema: expected object");
  }
  const fields = ["currency", "order_id", "quantity", "total_cents", "unit_price_cents"];
  const keys = Object.keys(order).sort();
  if (keys.length !== fields.length || keys.some((key, i) => key !== fields[i])) {
    throw Error("schema: missing or extra field");
  }
  if (typeof order.order_id !== "string" || !["USD", "EUR"].includes(order.currency) ||
      ![order.quantity, order.unit_price_cents, order.total_cents].every(Number.isInteger)) {
    throw Error("schema: invalid type or currency");
  }
  if (![order.quantity, order.unit_price_cents, order.total_cents].every(Number.isSafeInteger) ||
      order.quantity <= 0 || order.unit_price_cents < 0 || order.total_cents < 0) {
    throw Error("business: invalid range");
  }
  const total = order.quantity * order.unit_price_cents;
  if (!Number.isSafeInteger(total) || total !== order.total_cents) {
    throw Error("business: inconsistent total");
  }
  if (order.order_id !== expected.order_id || order.currency !== expected.currency) {
    throw Error("business: wrong order context");
  }
  return order;
}

Supply expected from a trusted job or application record, such as {order_id: "ORD-1042", currency: "USD"}. Taking it from the model's own output would make the identity check pointless. The function returns a candidate; source comparison and any authorized write are separate application steps.

For evolving or nested contracts, use a maintained JSON Schema validator rather than expanding this handwritten implementation. Set input-size limits at your transport boundary. JavaScript's ordinary parser also does not flag duplicate member names, so use a duplicate-key-rejecting parser if that distinction matters to your input policy.

Exercise the rejection paths

Wrap the synthetic valid order in this non-streaming fixture:

const expected = {order_id: "ORD-1042", currency: "USD"};
const good = {order_id: "ORD-1042", currency: "USD", quantity: 2,
              unit_price_cents: 1999, total_cents: 3998};
const completed = value => ({choices: [{finish_reason: "stop",
  message: {role: "assistant", content: JSON.stringify(value)}}]});
console.log(validateOrder(completed(good), expected));

Then change one condition at a time:

Change to this same fixture Expected result
No change Return the candidate order
Content has a trailing comma or Markdown fences Reject at syntax check
quantity: "2" Reject at schema check
Missing total_cents, an extra key, null, or an array Reject at schema check
quantity: -2 Reject at business range check
total_cents: 4998 Reject inconsistent total, despite schema conformance
order_id: "ORD-9999" Reject wrong order context
Integers outside JavaScript's safe range Reject before arithmetic is trusted
finish_reason: "length" or "content_filter" Reject incomplete or non-final output
Nonempty refusal or unresolved tool call Reject as an extraction result

A refusal can coexist with a normal-looking completion reason. Inspect the message as well as the finish reason. For Responses, use its status, incomplete_details, and typed output items; the Chat choices[0].message path does not apply. In a stream, wait for the relevant final response state and assemble the complete text before validation. A parseable prefix is not a completed order.

Recover according to the failure

Failure Next action
Unsupported schema or response-format parameter Check the selected model, endpoint, and supported schema subset. Correct the contract or select a documented supported route; do not retry unchanged or silently drop strict mode.
Truncated output Inspect the output budget and source size, then make a bounded new attempt when appropriate. Do not append guessed closing braces.
Refusal Return the appropriate refusal or review outcome; do not disguise it as a completed order or retry to bypass the refusal.
Parse or shape failure in JSON mode Keep the original source available and give a concise validation error to a limited correction attempt, if your workflow permits one.
Wrong total, identity, or source values Hold the candidate and check the source or authoritative application record. Route unresolved disagreement to review.

For a low-stakes extraction queue, one correction attempt for a formatting failure followed by manual review is a reasonable starting policy, not an API guarantee. Choose your limit from latency, cost, and error consequences. Revalidate the entire response after repair, and keep any action that creates an order outside the retry loop. Never “repair” a mismatched total silently: that hides whether the quantity, price, or total was extracted incorrectly.

Keep request IDs, schema version, failure category, and attempt relationships in your operational record. Avoid copying full order documents into ordinary error logs.

Verify the exact route before integrating it

An OpenAI-compatible endpoint accepting a basic chat request does not establish strict schema support. Use the compatibility checklist to record the provider/account, base URL, endpoint, exact model ID, client version, and required feature.

For Tokenhot configuration, the Quick Start documents the API base URL and authentication setup. Confirm response-format support separately for the route you choose. A model listing or HTTP 200 alone does not demonstrate that a strict contract is enforced.

Start locally with the ORD-1042 fixtures above. For a separately authorized, budgeted route test, verify a complete response and deliberately send an unsupported schema to check error handling. Keep that route check separate from application validation: even a successful strict-output request still needs the order-context and source checks before its data can be used.

Back to Blog
TokenHot

Chat, Image & Video Models with One API Key

  • Chat
  • Image
  • Video

Get discounted API rates on select AI models.

Get Your API Key

Pay-as-you-goOpenAI-compatible

Related Articles

OpenAI-Compatible APIs: What to Verify Before You Migrate

OpenAI-Compatible APIs: What to Verify Before You Migrate

October 4, 2026
MCP Tool Authorization After Login: A Layered Control Checklist

MCP Tool Authorization After Login: A Layered Control Checklist

September 18, 2026
How to Fix a Model Not Found Error in an LLM API

How to Fix a Model Not Found Error in an LLM API

November 30, 2026