Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.2 — Asking for JSON (and How Parsing Fails)
LLM Engineering · Example 1 of 1

A brace-counting extractor on six kinds of reply

Backticks are built with a repeat so the example needs no special quoting. Java uses the course's Json helper.

You can ask any model for JSON in the prompt, and it usually complies, but replies arrive in code fences, wrapped in chatter, with trailing commas, single quotes or cut off. A tolerant extractor handles the common cases, and knowing its limits tells you when you need more.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write strip_fence(text) that removes a leading line starting with three backticks and a trailing line of three backticks, and returns the inside. If there is no fence it returns the text unchanged.

02

Write is_cut_off(text) that returns True when the first { in the text never gets a matching } (count braces, ignoring strings is not needed for this version).

Explain it without notes

01

Name five ways a model's reply can break a JSON parser, and the fix for each.

02

Why is "take the text from the first { to the last }" a weaker extractor than counting braces?

03

Why not just repair trailing commas and single quotes automatically?

04

A parse error shows up only on long answers. What is the likely cause and how do you confirm it?

A brace-counting extractor on six kinds of reply
Sign in to run this example in your browser.

Expected output

clean           ok name=Ada age=36
code fence      ok name=Ada age=36
chatter         ok name=Ada age=36
trailing comma  invalid JSON
single quotes   invalid JSON
cut off         no complete object (cut off?)