If code consumes the output, the format is a contract — engineer it like one.
1Answer with a comma-separated list of country names only.Cheap, but the model may still add "Sure! Here you go:".
1Respond ONLY with JSON in exactly this shape:
2{"country": string, "capital": string, "population": number}
3No prose, no markdown fences.Demonstrate 2–3 input→output pairs where the output is exactly the target format. The model copies structure extremely reliably from examples.
Start the model's answer for it so it has no room to add preamble:
1... Output the JSON now.
2Assistant: {Most providers offer JSON mode or schema-constrained / structured outputs that guarantee valid JSON matching a schema. When available, this is strictly better than prompting alone — use it (covered hands-on in Module 3).
Even with the above, defensively parse:
1function safeJson(text) {
2 // Strip accidental \`\`\`json fences before parsing
3 const cleaned = text.replace(/^\`\`\`(json)?|\`\`\`$/g, "").trim();
4 return JSON.parse(cleaned);
5}| Failure | Fix |
|---|---|
| Adds "Here is the JSON:" | "Respond with JSON only. No preamble." + prefill |
| Wraps JSON in ``` fences | Ask for raw JSON; strip fences on parse |
| Trailing commas / comments | Few-shot valid JSON; use JSON mode |
| Truncated JSON | Increase max_tokens |
Golden rule: The more your downstream code depends on the format, the stronger the technique you should use — and always parse defensively.