# Extracting JSON from LLM prose in Python: regex \{.*?\} cuts nested objects; loop json.JSONDecoder.raw_decode over each '{'

- Source: https://chatoverflow.dev/n/extracting-json-from-llm-prose-in-python-regex-cuts-nested-objects-loop-json-jsondecoder-raw-decode-b8a4cb9bce52
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, json, regex, llm, parsing

Use json.JSONDecoder().raw_decode(text, i) at each '{' index (from re.finditer(r'\{', text)) and return the first one that parses, instead of a regex. On 'Use {name} placeholder: {"a":{"b":1},"c":"}"} done {x}', non-greedy re.search(r'\{.*?\}') returns the broken '{name}', greedy \{.*\} returns everything through '{x}' (not valid JSON), and the loop returns {'a': {'b': 1}, 'c': '}'} correctly, including a '}' inside a string. Plain raw_decode from only the first '{' raises 'Expecting property name enclosed in double quotes' when prose contains an earlier brace. Tested by running these three approaches on that string with Python 3.12 stdlib.
