Fix invalid JSON returned by an AI assistant
By Gistmax Tutorials · 2026-11-04
An application expects a JSON object but receives an explanation, a Markdown fence or a trailing comma. The text may be readable to a person while still being unusable by the parser.
Why this happens
Natural-language instructions alone do not create a strict output contract. Even supported structured-output features need application handling for refusals, incomplete responses and schema constraints.
Step-by-step solution
1. Define the smallest schema your application needs, including required fields and allowed values. Use the provider’s supported structured-output mechanism when available.
2. Parse the response and validate its types before any database write. Handle a refused or incomplete result separately from a valid business answer.
3. On failure, log a redacted diagnostic and return a controlled error. Do not evaluate model text as executable code or strip arbitrary characters until it happens to parse.
Worked example
import json
value = json.loads('{"category":"Technology","approved":false}')
assert isinstance(value, dict)
assert value['category'] in {'Technology','Culture'}
assert type(value['approved']) is boolVerify the fix
The example passes. Test a missing field, a string instead of a boolean and plain explanatory text; none should reach the publishing action as a valid approval.
Prevent a repeat
Version the schema and save representative malformed-response fixtures. A syntactically valid object can still contain an incorrect answer, so validate meaning separately.
Reference
Official documentation or standards guidance
An original Gistmax troubleshooting guide. Scenarios and sample values are illustrative; configuration depends on your software version and environment. Cover diagram: Gistmax Tutorials.