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:
- Define the schema, including allowed values for categories.
- Say what to do with missing data, for example use null.
- If your provider offers a JSON mode, schema mode or tool calling, use it, because it reduces syntax errors. Check the current API documentation.
- Parse the reply with a JSON library and check required fields.
- 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
StarterAny assistantMembers
Are AI-written phishing emails harder to spot, and what should I look for now?
Yes, AI can write clean, convincing phishing emails without the spelling mistakes people used to rely on, so judge the request and the sender, not the grammar.
privacy-safety
StarterAny assistantMembers
Can AI analyze my Excel or CSV data and can I trust the results?
Often yes, especially with assistants that can run code on uploaded files, but you should verify the results.
accuracy
StarterAny assistantMembers
Can an AI assistant be tricked by hidden instructions in emails or web pages?
Yes. If an assistant reads emails, web pages or documents, hidden text in them can try to give it new instructions, which is called prompt injection.
privacy-safety