Parsing Safely
Explore how to parse AI-generated JSON safely by managing common formatting artifacts like Markdown code fences. Learn to use json.loads with robust error handling to avoid crashes from malformed data. Understand that successful parsing does not guarantee data correctness, preparing you to validate values explicitly in subsequent steps.
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 ...