Skip to content

Messy replies

Read · 1 of 3

Models add wrapping

Ask for JSON and you'll often get Sure! Here it is: followed by the JSON inside a ```json code fence, sometimes with a closing remark.

json.loads on the whole reply crashes. The fix is to find where the object starts and decode just that. Python's json.JSONDecoder().raw_decode reads one complete value and tells you where it ended, so trailing text doesn't matter.

(Better still, models with tool use return arguments as already-parsed JSON. You'll use that from module 3. But you'll still meet messy text everywhere else.)

Read this lesson as text

Code fences, chatty sentences, stray braces: dig the JSON out anyway.

Models add wrapping

Ask for JSON and you'll often get Sure! Here it is: followed by the JSON inside a ```json code fence, sometimes with a closing remark.

json.loads on the whole reply crashes. The fix is to find where the object starts and decode just that. Python's json.JSONDecoder().raw_decode reads one complete value and tells you where it ended, so trailing text doesn't matter.

(Better still, models with tool use return arguments as already-parsed JSON. You'll use that from module 3. But you'll still meet messy text everywhere else.)

Break it: Break the extractor

This extractor takes everything from the first { to the last } and parses it, then prints the answer field.

Find a reply where it fails, while a careful extractor still finds the answer.

import json

text = input()
print(json.loads(text[text.find("{"): text.rfind("}") + 1])["answer"])

Input rules: One line: the model's reply, containing a JSON object with a text "answer" field somewhere in it.

Exercise: A sturdy extractor

Read the whole reply (it can span several lines). Find the first JSON object that has a city field and print that field.

The object may sit inside a code fence, with text before it, and even text containing { or } after it.