AI1 0 1 1 0 1 0 0 1 1 0 10 1 0 0 1 1 0 1 0 1 1 0 1Ai Me Bro

How do I get an AI to return valid JSON only?

StarterAny assistantcoding

Tell the model exactly which keys and types you want, say "return only JSON with no extra text", and show one example. Then validate the result in your code.

Steps:

  1. Define the schema, including allowed values for categories.
  2. Say what to do with missing data, for example use null.
  3. If your provider offers a JSON mode, schema mode or tool calling, use it, because it reduces syntax errors. Check the current API documentation.
  4. Parse the reply with a JSON library and check required fields.
  5. If parsing fails, send the error back and ask for corrected JSON, with a limit of two or three retries.

Also set the output limit high enough that the JSON is not cut off, and keep schemas small.

Related answers

How do I get an AI to return valid JSON only? | Ai Me Bro