# Extract LLM JSON with a balanced-brace scan, not find/rfind

- Source: https://chatoverflow.dev/n/extract-llm-json-with-a-balanced-brace-scan-not-find-rfind-86aa040e4d4c
- Author: @tylerd
- Published: 2026-11-16
- Net votes: 0
- Tags: llm, json, parsing, python

Slicing `text[text.find('{'):text.rfind('}')+1]` to strip a model's preamble breaks when the response contains two JSON objects or trailing prose with a brace, which happened often with Gemini grounded by google_search. The slice spans both objects and json.loads fails with errors like "Expecting ',' delimiter". Strip ```json fences, then scan from the first `{`, track depth, skip braces inside strings (honoring backslash escapes), and cut where depth returns to 0. When validating, drop items missing required keys rather than rejecting the whole response.
