DeepSeek JSON mode asks the API to return valid JSON, but production code must still handle empty content, truncation and semantically invalid values. Set response_format to json_object, say “json” in the prompt, show the desired shape, allocate enough output and validate the parsed object against your schema.

Minimal request

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {
            "role": "system",
            "content": (
                "Return json with exactly these keys: "
                '{"label":"positive|neutral|negative","confidence":0.0}.'
            ),
        },
        {"role": "user", "content": "Classify: The update works as expected."},
    ],
    response_format={"type": "json_object"},
    max_tokens=100,
    extra_body={"thinking": {"type": "disabled"}},
)

if response.choices[0].finish_reason != "stop":
    raise RuntimeError("Incomplete JSON response")

raw = response.choices[0].message.content
if not raw:
    raise RuntimeError("Empty JSON response")

data = json.loads(raw)

Parsing is only the first validation layer.

Validate a schema

With jsonschema:

from jsonschema import validate

schema = {
    "type": "object",
    "properties": {
        "label": {"enum": ["positive", "neutral", "negative"]},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1},
    },
    "required": ["label", "confidence"],
    "additionalProperties": False,
}

validate(instance=data, schema=schema)

Then apply business rules. A confidence value inside 0–1 is syntactically valid but not necessarily calibrated. A valid date can fall outside an allowed period.

DeepSeek’s documented requirements

The official guide says to set response_format to json_object, include “json” in the system or user prompt, provide an example and choose enough max_tokens to avoid truncation. It also warns that the feature can occasionally return empty content.

Treat these as expected failure modes. Do not write json.loads(response.content) without checking finish reason and emptiness.

Truncation handling

If finish_reason is length, do not append a brace and accept the object. The missing content could change meaning. Increase the output budget, reduce requested fields or split the task.

For large extraction jobs, process bounded batches with stable identifiers and validate each one. Require the model to return source locations so records can be reconciled against the original document.

Repair strategy

Allow at most one or two repair attempts. Send the validation error and the original desired schema, not a vague “fix it.” Do not feed an enormous malformed response back repeatedly.

If repair fails, route the record to human review or a deterministic parser. Record failure metrics. Silent fallback to an unvalidated object turns a rare model error into corrupted data.

JSON is not evidence

Structured output can still contain hallucinated names, prices or citations. Separate extraction from verification. If the task uses a supplied document, require page or field references and compare them programmatically where possible.

For changing facts, fetch from an authoritative API or database rather than asking a language model to recall them. Use DeepSeek to transform verified data, not replace the source of truth.

Security controls

Limit input and output size. Reject keys not in the schema. Do not use JSON values as SQL, paths, HTML or commands without context-specific escaping and allow-lists. Strings can contain prompt injection, scripts or traversal sequences.

If JSON selects a tool, apply the tool-calling safeguards. Schema validity does not authorise an action.

Arrays and bulk extraction

Specify maximum array length and item schema. Ask for stable source IDs rather than relying on order. Check duplicates, missing items and totals after validation.

A response with ten valid objects is not complete when the source had twelve records. Compare returned IDs against an expected set and make omissions explicit.

Type coercion

Do not silently convert "false" to true because it is a non-empty string, or "1,200" to a number without locale rules. Require native JSON booleans and numbers. Reject ambiguous dates; use ISO 8601 where applicable.

Normalisation should be deterministic code. The model can suggest a mapping, but the application owns final types.

Observability

Track parse failure, schema failure, business-rule failure, empty response, truncation and repair success by model and prompt version. Store a redacted sample for debugging only when policy allows.

Run a regression set after model updates. Structured output reliability can change even when the API shape remains compatible.

For end-to-end request setup, start with the DeepSeek API guide. Teams using a compatibility client should also review the OpenAI SDK configuration rather than assuming every structured-output option maps identically.

Conclusion

DeepSeek JSON mode is a formatting aid, not a data guarantee. Check finish reason, parse, validate a strict schema, enforce business rules and stop after bounded repairs. Keep authoritative facts outside the model whenever possible.

Keep representative valid, invalid, empty and truncated responses in a redacted regression suite. Run it whenever the model, prompt, SDK or schema changes so a small update cannot silently corrupt downstream records.

Useful next steps

Continue with related guidance

Put this page in context with DeepSeek API Guide: Setup, Keys and First Request, Use DeepSeek With the OpenAI SDK, DeepSeek Tool Calling Guide, and DeepSeek API Errors and Troubleshooting. These links cover the broader decision and the closest follow-up topics without repeating this article.

Common questions

Frequently asked questions

Does JSON mode guarantee my schema?

It aims for valid JSON, not necessarily your complete business schema. Validate separately.

What should I do with empty content?

Treat it as a documented failure mode, retry within a limit and then fail safely.

Can I repair truncated JSON manually?

Do not guess missing content. Reduce the task or rerun with an adequate budget.

Is strict tool mode the same as JSON output?

No. Tool-call strict mode is a separate beta schema feature with its own limits.

Evidence

Sources

3 primary references
  1. JSON Output — official external destination

    DeepSeek · official API documentation · verified July 30, 2026

  2. Your First API Call — official external destination

    DeepSeek · official API documentation · verified July 30, 2026

  3. Tool Calls — official external destination

    DeepSeek · official API documentation · verified July 30, 2026

Continue reading