<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: flow nears</title>
    <description>The latest articles on DEV Community by flow nears (@nearshi).</description>
    <link>https://dev.to/nearshi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4130188%2F14bbbaf9-fc38-4e58-8ebb-cbb64255c00b.png</url>
      <title>DEV Community: flow nears</title>
      <link>https://dev.to/nearshi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nearshi"/>
    <language>en</language>
    <item>
      <title>Clean JSON Extraction with Ollama and Python</title>
      <dc:creator>flow nears</dc:creator>
      <pubDate>Thu, 17 Sep 2026 15:55:56 +0000</pubDate>
      <link>https://dev.to/nearshi/-clean-json-extraction-with-ollama-and-python-21f3</link>
      <guid>https://dev.to/nearshi/-clean-json-extraction-with-ollama-and-python-21f3</guid>
      <description>&lt;p&gt;When building autonomous agents or production workflows with local LLMs via &lt;strong&gt;Ollama&lt;/strong&gt;, one of the most persistent engineering challenges is output parsing. Even when instructed to produce pure JSON, smaller models like &lt;code&gt;llama3:8b&lt;/code&gt;, &lt;code&gt;mistral:7b&lt;/code&gt;, or &lt;code&gt;phi3&lt;/code&gt; often output markdown code fences (&lt;br&gt;
&lt;br&gt;
&lt;code&gt;json ...&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
), conversational text preambles, or incomplete payloads.&lt;/p&gt;

&lt;p&gt;In this article, we will explore a robust, zero-dependency Python pattern using &lt;strong&gt;Anchor Tag Framing&lt;/strong&gt; and dynamic boundary isolation to extract 100% valid JSON from Ollama text streams.&lt;/p&gt;


&lt;h2&gt;
  
  
  The Problem: Fine-Tuning Artifacts in Small LLMs
&lt;/h2&gt;

&lt;p&gt;Open-source LLMs are heavily fine-tuned on chat datasets and markdown documentation. When you prompt a model to return JSON:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;ollama&lt;/span&gt;

&lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ollama&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;llama3&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;role&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;user&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Extract user info from text: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;John Doe, 29, Software Engineer&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;. Return JSON.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;message&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You frequently receive output like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Here is the extracted information in JSON format:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
json&lt;br&gt;
{&lt;br&gt;
  "name": "John Doe",&lt;br&gt;
  "age": 29,&lt;br&gt;
  "occupation": "Software Engineer"&lt;br&gt;
}&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hope this helps!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
python&lt;/p&gt;

&lt;p&gt;If you feed &lt;code&gt;response['message']['content']&lt;/code&gt; directly into &lt;code&gt;json.loads()&lt;/code&gt;, your application raises a &lt;code&gt;json.decoder.JSONDecodeError&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Relying on regex fallbacks or generic string replaces (&lt;code&gt;replace("&lt;/code&gt;`&lt;code&gt;json", "")&lt;/code&gt;) is fragile—especially when model responses contain nested code blocks or escaped quotes.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Solution: Anchor Tag Framing
&lt;/h2&gt;

&lt;p&gt;Instead of negative constraints ("&lt;em&gt;Do not include markdown&lt;/em&gt;"), we use &lt;strong&gt;Anchor Tag Framing&lt;/strong&gt;. By instructing the model to place its JSON payload strictly inside unique, non-colliding XML-style execution tags, we establish a deterministic structural boundary.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. The Prompt Template
&lt;/h3&gt;

&lt;p&gt;Define a clear system contract containing explicit &lt;code&gt;&amp;lt;payload&amp;gt;&lt;/code&gt; boundary tags:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;python&lt;br&gt;
SYSTEM_PROMPT = """&lt;br&gt;
You are a specialized data extraction API that ONLY outputs valid JSON.&lt;/p&gt;

&lt;p&gt;STRICT EXECUTION RULES:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Do not include any introductory text, preambles, explanations, or postscript text.&lt;/li&gt;
&lt;li&gt;Do not use markdown code fences (e.g., &lt;code&gt;&lt;/code&gt;&lt;code&gt;json or&lt;/code&gt;&lt;code&gt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Output the raw JSON payload exclusively within the execution boundary  and .&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example format:&lt;br&gt;
&lt;br&gt;
{&lt;br&gt;
  "key": "value"&lt;br&gt;
}&lt;br&gt;
&lt;br&gt;
"""&lt;br&gt;
&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Robust Python Extractor Function
&lt;/h3&gt;

&lt;p&gt;Next, build a lightweight parser in Python that extracts content strictly within the target tags, falling back gracefully if needed:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;python&lt;br&gt;
import json&lt;br&gt;
import re&lt;br&gt;
from typing import Any, Dict&lt;br&gt;
import ollama&lt;/p&gt;

&lt;p&gt;def extract_json_payload(raw_text: str) -&amp;gt; Dict[str, Any]:&lt;br&gt;
    """Extracts and parses JSON located inside  tags.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Falls back to regex searching for raw JSON objects if tags are missing.
"""
# 1. Primary Extraction: Boundary Tags
tag_pattern = r"&amp;lt;payload&amp;gt;\s*(\{.*\}|\[.*\])\s*&amp;lt;/payload&amp;gt;"
match = re.search(tag_pattern, raw_text, re.DOTALL)

if match:
    json_str = match.group(1)
else:
    # 2. Fallback: Search for first opening brace/bracket to last closing brace/bracket
    fallback_pattern = r"(\{.*\}|\[.*\])"
    fallback_match = re.search(fallback_pattern, raw_text, re.DOTALL)
    if fallback_match:
        json_str = fallback_match.group(1)
    else:
        raise ValueError("No JSON payload detected in response.")

# 3. Parse JSON
return json.loads(json_str.strip())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;




&lt;h2&gt;
  
  
  End-to-End Implementation Example
&lt;/h2&gt;

&lt;p&gt;Here is a complete, runnable script demonstrating the extraction pipeline:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;python&lt;br&gt;
import json&lt;br&gt;
import re&lt;br&gt;
import ollama&lt;/p&gt;

&lt;p&gt;def query_ollama_json(user_text: str) -&amp;gt; dict:&lt;br&gt;
    system_instruction = """&lt;br&gt;
    You are a structural parser API. Transform input text into structured JSON.&lt;br&gt;
    Output ONLY within the  and  tags.&lt;br&gt;
    """&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user_prompt = f"""
Extract key attributes from the following text into JSON format (keys: 'name', 'role', 'skills'):

"{user_text}"
"""

response = ollama.chat(
    model="llama3",
    messages=[
        {"role": "system", "content": system_instruction},
        {"role": "user", "content": user_prompt},
    ],
)

content = response["message"]["content"]
return extract_json_payload(content)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h1&gt;
  
  
  --- Execution ---
&lt;/h1&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    raw_input = "Alice Smith is a Senior DevOps Engineer skilled in Docker, Kubernetes, and Python."&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    structured_data = query_ollama_json(raw_input)
    print("Successfully extracted JSON:")
    print(json.dumps(structured_data, indent=2))
except Exception as e:
    print(f"Extraction failed: {e}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;




&lt;h2&gt;
  
  
  Why This Technique Works Under the Hood
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Attention Focusing:&lt;/strong&gt; Small LLMs pay higher attention to token sequences with distinct boundary delimiters (&lt;code&gt;&amp;lt;tag&amp;gt;&lt;/code&gt; vs &lt;code&gt;&amp;lt;/tag&amp;gt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deterministic Context Window:&lt;/strong&gt; By shifting the target output pattern to standard tag structures, you minimize the activation of conversational completion tokens learned during post-training fine-tuning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Regex Isolation:&lt;/strong&gt; Extracting via fixed string boundaries eliminates false positives from nested quotes or markdown formatting in text fields.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  References &amp;amp; Further Reading
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/ollama/ollama" rel="noopener noreferrer"&gt;Ollama Official Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://flownear.gumroad.com/l/gkmfat" rel="noopener noreferrer"&gt;EdgeJSON Prompt &amp;amp; Modelfile Pack&lt;/a&gt; — &lt;em&gt;A collection of 40+ production-ready prompts, Ollama Modelfiles, and validation schemas for deterministic JSON generation.&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>llm</category>
      <category>programming</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Clean JSON Extraction with Ollama and Python</title>
      <dc:creator>flow nears</dc:creator>
      <pubDate>Thu, 17 Sep 2026 15:53:22 +0000</pubDate>
      <link>https://dev.to/nearshi/clean-json-extraction-with-ollama-and-python-3202</link>
      <guid>https://dev.to/nearshi/clean-json-extraction-with-ollama-and-python-3202</guid>
      <description>&lt;h1&gt;
  
  
  Clean JSON Extraction with Ollama and Python
&lt;/h1&gt;

&lt;p&gt;When building autonomous agents or production workflows with local LLMs via &lt;strong&gt;Ollama&lt;/strong&gt;, one of the most persistent engineering challenges is output parsing. Even when instructed to produce pure JSON, smaller models like &lt;code&gt;llama3:8b&lt;/code&gt;, &lt;code&gt;mistral:7b&lt;/code&gt;, or &lt;code&gt;phi3&lt;/code&gt; often output markdown code fences (&lt;br&gt;
&lt;br&gt;
&lt;code&gt;json ...&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
), conversational text preambles, or incomplete payloads.&lt;/p&gt;

&lt;p&gt;In this article, we will explore a robust, zero-dependency Python pattern using &lt;strong&gt;Anchor Tag Framing&lt;/strong&gt; and dynamic boundary isolation to extract 100% valid JSON from Ollama text streams.&lt;/p&gt;


&lt;h2&gt;
  
  
  The Problem: Fine-Tuning Artifacts in Small LLMs
&lt;/h2&gt;

&lt;p&gt;Open-source LLMs are heavily fine-tuned on chat datasets and markdown documentation. When you prompt a model to return JSON:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;ollama&lt;/span&gt;

&lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ollama&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;llama3&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;role&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;user&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Extract user info from text: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;John Doe, 29, Software Engineer&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;. Return JSON.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;message&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You frequently receive output like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Here is the extracted information in JSON format:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
json&lt;br&gt;
{&lt;br&gt;
  "name": "John Doe",&lt;br&gt;
  "age": 29,&lt;br&gt;
  "occupation": "Software Engineer"&lt;br&gt;
}&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hope this helps!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
python&lt;/p&gt;

&lt;p&gt;If you feed &lt;code&gt;response['message']['content']&lt;/code&gt; directly into &lt;code&gt;json.loads()&lt;/code&gt;, your application raises a &lt;code&gt;json.decoder.JSONDecodeError&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Relying on regex fallbacks or generic string replaces (&lt;code&gt;replace("&lt;/code&gt;`&lt;code&gt;json", "")&lt;/code&gt;) is fragile—especially when model responses contain nested code blocks or escaped quotes.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Solution: Anchor Tag Framing
&lt;/h2&gt;

&lt;p&gt;Instead of negative constraints ("&lt;em&gt;Do not include markdown&lt;/em&gt;"), we use &lt;strong&gt;Anchor Tag Framing&lt;/strong&gt;. By instructing the model to place its JSON payload strictly inside unique, non-colliding XML-style execution tags, we establish a deterministic structural boundary.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. The Prompt Template
&lt;/h3&gt;

&lt;p&gt;Define a clear system contract containing explicit &lt;code&gt;&amp;lt;payload&amp;gt;&lt;/code&gt; boundary tags:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;python&lt;br&gt;
SYSTEM_PROMPT = """&lt;br&gt;
You are a specialized data extraction API that ONLY outputs valid JSON.&lt;/p&gt;

&lt;p&gt;STRICT EXECUTION RULES:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Do not include any introductory text, preambles, explanations, or postscript text.&lt;/li&gt;
&lt;li&gt;Do not use markdown code fences (e.g., &lt;code&gt;&lt;/code&gt;&lt;code&gt;json or&lt;/code&gt;&lt;code&gt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Output the raw JSON payload exclusively within the execution boundary  and .&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example format:&lt;br&gt;
&lt;br&gt;
{&lt;br&gt;
  "key": "value"&lt;br&gt;
}&lt;br&gt;
&lt;br&gt;
"""&lt;br&gt;
&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Robust Python Extractor Function
&lt;/h3&gt;

&lt;p&gt;Next, build a lightweight parser in Python that extracts content strictly within the target tags, falling back gracefully if needed:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;python&lt;br&gt;
import json&lt;br&gt;
import re&lt;br&gt;
from typing import Any, Dict&lt;br&gt;
import ollama&lt;/p&gt;

&lt;p&gt;def extract_json_payload(raw_text: str) -&amp;gt; Dict[str, Any]:&lt;br&gt;
    """Extracts and parses JSON located inside  tags.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Falls back to regex searching for raw JSON objects if tags are missing.
"""
# 1. Primary Extraction: Boundary Tags
tag_pattern = r"&amp;lt;payload&amp;gt;\s*(\{.*\}|\[.*\])\s*&amp;lt;/payload&amp;gt;"
match = re.search(tag_pattern, raw_text, re.DOTALL)

if match:
    json_str = match.group(1)
else:
    # 2. Fallback: Search for first opening brace/bracket to last closing brace/bracket
    fallback_pattern = r"(\{.*\}|\[.*\])"
    fallback_match = re.search(fallback_pattern, raw_text, re.DOTALL)
    if fallback_match:
        json_str = fallback_match.group(1)
    else:
        raise ValueError("No JSON payload detected in response.")

# 3. Parse JSON
return json.loads(json_str.strip())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;




&lt;h2&gt;
  
  
  End-to-End Implementation Example
&lt;/h2&gt;

&lt;p&gt;Here is a complete, runnable script demonstrating the extraction pipeline:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;python&lt;br&gt;
import json&lt;br&gt;
import re&lt;br&gt;
import ollama&lt;/p&gt;

&lt;p&gt;def query_ollama_json(user_text: str) -&amp;gt; dict:&lt;br&gt;
    system_instruction = """&lt;br&gt;
    You are a structural parser API. Transform input text into structured JSON.&lt;br&gt;
    Output ONLY within the  and  tags.&lt;br&gt;
    """&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user_prompt = f"""
Extract key attributes from the following text into JSON format (keys: 'name', 'role', 'skills'):

"{user_text}"
"""

response = ollama.chat(
    model="llama3",
    messages=[
        {"role": "system", "content": system_instruction},
        {"role": "user", "content": user_prompt},
    ],
)

content = response["message"]["content"]
return extract_json_payload(content)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h1&gt;
  
  
  --- Execution ---
&lt;/h1&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    raw_input = "Alice Smith is a Senior DevOps Engineer skilled in Docker, Kubernetes, and Python."&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    structured_data = query_ollama_json(raw_input)
    print("Successfully extracted JSON:")
    print(json.dumps(structured_data, indent=2))
except Exception as e:
    print(f"Extraction failed: {e}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;




&lt;h2&gt;
  
  
  Why This Technique Works Under the Hood
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Attention Focusing:&lt;/strong&gt; Small LLMs pay higher attention to token sequences with distinct boundary delimiters (&lt;code&gt;&amp;lt;tag&amp;gt;&lt;/code&gt; vs &lt;code&gt;&amp;lt;/tag&amp;gt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deterministic Context Window:&lt;/strong&gt; By shifting the target output pattern to standard tag structures, you minimize the activation of conversational completion tokens learned during post-training fine-tuning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Regex Isolation:&lt;/strong&gt; Extracting via fixed string boundaries eliminates false positives from nested quotes or markdown formatting in text fields.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  References &amp;amp; Further Reading
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/ollama/ollama" rel="noopener noreferrer"&gt;Ollama Official Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;[EdgeJSON Prompt &amp;amp; Modelfile Pack] &lt;a href="https://flownear.gumroad.com/l/gkmfat" rel="noopener noreferrer"&gt;https://flownear.gumroad.com/l/gkmfat&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
    </item>
  </channel>
</rss>
