Guides

DeepSeek JSON Output: Parse It, Then Validate the Data

Use DeepSeek JSON mode for a small extraction task and reject blank, truncated, or structurally wrong results before they reach your application.

On this page
  1. Define a small contract first
  2. Keep syntax, schema, and truth separate
  3. Recover without silently inventing data

Valid JSON is not the same as correct data. DeepSeek’s JSON mode helps with the format, but your code still needs to check required fields, types, and whether values are supported by the input.

We checked the official JSON-output guide on November 1, 2026. It requires response_format={"type": "json_object"}, a prompt that explicitly asks for JSON, and enough output space. It also describes blank-looking content as a possible failure case. The following example is documentation-based, not a live API result.

Define a small contract first

Suppose a support form contains one product and an optional order number. Our contract has exactly two keys, both strings, with an empty string for a missing order number. This is an application decision, not a property supplied automatically by JSON mode.

Install openai in a Python environment, then save this script:

import getpass
import json
from openai import OpenAI

source = "My Cedar desk lamp flickers. I cannot find the order number."
client = OpenAI(api_key=getpass.getpass("DeepSeek key: "),
                base_url="https://api.deepseek.com", max_retries=0)
response = client.chat.completions.create(
    model="deepseek-flash",
    response_format={"type": "json_object"},
    max_tokens=1024,
    messages=[
        {"role": "system", "content": (
            'Return JSON with exactly these string keys: '
            '"product" and "order_number". Extract only from the input. '
            'Use an empty string when absent. Example JSON: '
            '{"product":"paper tray","order_number":""}.'
        )},
        {"role": "user", "content": source},
    ],
)
choice = response.choices[0]
raw = choice.message.content or ""
if choice.finish_reason != "stop" or not raw.strip():
    raise SystemExit("Blank or incomplete output; do not store it.")
try:
    data = json.loads(raw)
except json.JSONDecodeError:
    raise SystemExit("The answer did not parse as JSON.")
required = {"product", "order_number"}
if not isinstance(data, dict) or set(data) != required:
    raise SystemExit("Wrong object shape.")
if not all(isinstance(value, str) for value in data.values()):
    raise SystemExit("Every field must be a string.")
if not data["product"] or data["product"].lower() not in source.lower():
    raise SystemExit("Product is missing or not supported by the test input.")
if data["order_number"]:
    raise SystemExit("Unexpected order number for this known test input.")
print(data)

The example checks a known fixture. For real inputs, replace its final fixture-specific check with your business rules; do not reject every nonempty order number. A production extractor also needs a policy for ambiguous or multiple products.

Keep syntax, schema, and truth separate

Layer Example failure Your check
Syntax Unclosed object JSON parser
Shape A list instead of an object Keys and types
Meaning An invented order number Compare with source evidence

Even an object that passes all structural checks can contain a wrong product name. Keep the original form text available for review rather than overwriting it with the extracted fields.

Recover without silently inventing data

Do not fill a missing order number with a random identifier. Do not repair truncated JSON by appending braces and assuming the contents are complete. If you retry, bound the number of attempts and retain a failure state when validation still fails.

For larger documents, first establish what one record means and how repeated items should be represented. Expanding this two-field example into a whole invoice parser requires more than adding keys to the prompt.

If your connection has not worked yet, start with the DeepSeek Python setup guide. Fix authentication separately from extraction correctness.

Sources & references

Written by Modelrovia Editorial. Our standards distinguish official claims from observed results.

How we research and test →

Tools in this article