How to Get Clean JSON Output from DeepSeek API Without Markdown Fences?

Asked 4 hours ago Updated 3 hours ago 24 views

1

Using DeepSeek's API for a small tool. I ask for JSON and it keeps wrapping the output in ```json fences or adding "Here is your JSON:" before it. My parser dies every time. How do I make it behave?

1 Answer


1

Three things, do all of them.

  • Turn on JSON mode in the API call if it's available for the model you're using. That forces valid JSON.
  • In your system prompt, be blunt: "Output only a raw JSON object. No explanation. No markdown. No code fences." And give it an example of the exact shape you want, that helps more than any instruction.
  • And then, this is the part everyone skips, assume it'll still mess up sometimes. Before parsing, strip anything that looks like ``` from the start and end. Wrap the parse in try/except. If it fails, send the bad output back with "fix this so it's valid JSON" or just retry. No model gets formatting right 100% of the time, so build for that instead of hoping.

Write Your Answer