All guides

Get JSON from DeepSeek and validate the fields

Follow the official JSON Output notes: set response_format, the prompt and max_tokens, then parse, check fields and handle blank content in your own code.

AINavWritten / Updated Sources checked
On this page

At a glance

When a program must read a model result directly, free text is hard to handle. DeepSeek's JSON Output is meant to make the model return a parseable JSON string. This guide walks through one full task: write the request, read the reply, check the fields, and stop or retry on blank content or a parse failure. The field names and sample text are invented teaching material and contain no real user data.

Workflow

  1. Does the request meet the JSON conditions?

    Confirm response_format is {'type': 'json_object'}, the prompt contains the word json with an example, and max_tokens is reasonable.

  2. Can the reply be parsed?

    Check whether content is only spaces. The docs say content not recognized as JSON is replaced with spaces, even when finish_reason is stop.

  3. Do the fields match your contract?

    A parseable reply can still lack fields, so your own code checks field names, types and allowed values.

Each stage cites official sources.

Before you start

  • A Python environment that can call the DeepSeek API using the openai library and base_url https://api.deepseek.com as in the official sample; keep the key in local configuration, not in prompts or logs.
  • A short test text without personal information, plus a written list of the JSON fields and types you expect, for example topic as a string and owner as a string.

1. Write the target JSON shape

In a local note, fix the fields first, for example {"topic": "...", "owner": "..."}. This contract feeds both the prompt example and the validation code, so the two must agree.

2. Put json and an example in the prompt

In the system or user prompt, include the word json, say what should be parsed, and add one example input with its example JSON output. The official page lists this as a requirement for JSON Output.

3. Set response_format and max_tokens

In the chat.completions.create call, pass response_format={'type': 'json_object'} and set max_tokens high enough for the complete JSON so the string is not cut off midway. The official sample uses the model name deepseek-flash; follow your current documentation.

4. Test for blank content first

Read response.choices[0].message.content and call strip() before anything else. If it is empty, do not call json.loads; mark the attempt as failed and handle it under the retry limit in step 6.

5. Parse and validate the fields

Only for non-empty content, use json.loads inside try/except and catch json.JSONDecodeError (for example when the JSON was truncated). After a successful parse, check that required fields exist, have the right types, and are not empty strings you do not accept. Treat a parse exception or any field failure as a failed attempt, and do not quietly fill defaults.

6. Set retry and stop rules

Blank content, a parse exception and failed validation all go to the same failure branch: you may adjust the prompt and retry, and the docs suggest handling blank content in code. Set your own cap, such as one or two retries. After that, stop, record the reason and hand the case to a person so the code does not loop forever.

Original example

Invented input: "Weekly sync moved to Thursday; Mira will send the agenda." Prompt gist: the system message says The user will provide a short note. Output json with the fields topic and owner., followed by one example input and example JSON. Request parameters: response_format={'type': 'json_object'}, with max_tokens large enough for two short fields. Shape you expect (a checking standard, not a recorded output): {"topic": "Weekly sync moved to Thursday", "owner": "Mira"} Validation idea (check blank first, then parse, all failures share one branch): content = response.choices[0].message.content or "" ok = False if content.strip(): try: data = json.loads(content) ok = (isinstance(data, dict) and isinstance(data.get("topic"), str) and data["topic"].strip() != "" and isinstance(data.get("owner"), str) and data["owner"].strip() != "") except json.JSONDecodeError: ok = False if not ok: # log the reason; retry while attempts is under your cap, otherwise stop and hand off to a person pass This way blank content never reaches json.loads, and truncated JSON does not crash the program.

Completion checks

  • The prompt really contains the word json and an example JSON.
  • content is non-empty after stripping spaces before it reaches json.loads.
  • json.JSONDecodeError is caught and goes to the same failure branch as blank content and failed field checks.
  • Parsed field names and types match the contract from step 1, item by item.
  • max_tokens is large enough that the JSON is not truncated; the retry count has a cap, and failure logs hold no key or real personal data.

Limits

  • The official material says JSON Output yields valid JSON strings; it does not promise that every field is present or correct, so field validation is your job.
  • Blank content can appear even when finish_reason is stop, so the finish reason alone does not prove success.
  • This guide gives no success rates and does not claim any prompt always avoids blank replies.

Verification scope

Only the official DeepSeek JSON Output documentation was read. Login, installation, product API execution, file upload and generated output were not tested; the fields and validation code are original illustrative samples, not real run output.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. DeepSeek · Official sources
    View details