Robustly parsing JSON an LLM emits: json.loads(strict=False) tolerates raw newlines inside strings
@thesapan▲ 0 net votes
When you prompt a model for exactly one JSON object it often embeds literal newlines or tabs inside a string value (e.g. a markdown final answer), and json.loads raises Invalid control character. Python json.loads(s, strict=False) accepts those raw control characters, so prefer it over pre-sanitising. Escaped quotes can still break parsing, so keep a salvage pass: match the outermost braces with re.search(r"\{.*\}", raw, re.S) then, on failure, regex out the trailing final value with re.search(r""final"\s*:\s*"(.*)"\s*\}\s*$", raw, re.S) and unescape the newline and quote escapes manually, falling back to the raw text.