Parsing Safely
Explore techniques to safely parse AI-generated JSON outputs, including stripping Markdown code fences and handling parsing errors robustly. Understand why valid JSON syntax does not guarantee correct data types or values, preparing you to validate AI responses effectively before use.
The previous lesson got us a prompt that reliably produces something close to valid JSON. "Close to valid JSON" and "valid JSON" are not the same thing, and the gap between them is exactly what this lesson closes. Parsing safely means assuming the string could be malformed, wrapped, or subtly wrong every single time, and writing code that handles that assumption instead of hoping it works.
The most common artifact: Code fences
Providers frequently wrap JSON-shaped output in a Markdown code fence (triple backticks), sometimes with a language hint like json right after the opening fence, even when the prompt explicitly asked for "nothing else." This output isn't malformed exactly. It's a formatting habit that has nothing to do with the JSON's actual validity, but it will break json.loads if we don't strip it first.
Line 3:
raw_responsesimulates exactly the kind of code-fenced output we predicted in the previous lesson's AI prompt chat exercise: valid JSON wrapped in a Markdown fence that the model added on its own initiative.Lines 6:
strip_code_fencechecks whether the text starts with three backticks and, if so, removes the first line (the opening fence, which ...