Digging the JSON Out of the Reply

parsing JSON out of a reply

Part of: Structured JSON Extractor

You asked for JSON and only JSON. The model, being helpful, often returns Sure! Here is the contact: and then the JSON, or wraps it in a Markdown code fence. Feed that straight to json.loads and it throws. The fix is to stop trusting the reply to be clean and instead dig the JSON object out of whatever came back. The reply is rarely bare JSON Three shapes you'll see constantly: - Chatty prefix: Here's what I found:\n{"name": "Ada"} - Code fence: three backticks, json, the object, three backticks. - Trailing note: {"name": "Ada"} Let me know if you need more! Find the object by its braces A JSON object starts at the first { and ends at the last }. Slice between them and you've dropped the prose on either side: find gives the first opening brace, rfind the last closing brace. Everything before start and after end is chatter you throw away. This handles the code fence too. Backticks live outside the braces, so the slice skips them. Then parse the slice Parsing the slice instead of the raw reply is the whole trick. json.loads(raw) chokes on the prefix. json.loads(extract json(raw)) doesn't, because the prefix is gone. Why not just ask the model to stop adding text? You do, in the promp

Challenge: Dig Out the JSON