LlmJsonExtractor
Helpers & Utilities · AiDotNet.Agentic.Pipeline
Pulls the JSON object out of a model reply that may wrap it in prose or a code fence.
For Beginners
You asked the AI for a JSON answer and it replied with JSON plus a sentence of explanation, or wrapped it in a code block. This digs out the JSON and hands it back. If nothing in the reply is valid JSON, it tells you so rather than throwing, which lets a caller retry or fall back instead of crashing.
How It Works
A model asked for JSON often answers with JSON surrounded by something else: a fenced block, a sentence of
preamble, a closing remark. This finds the object regardless. The first choice is always to make the reply
unambiguous at the source — set ResponseFormat to
JsonSchema and supply
ResponseJsonSchema, which providers with constrained decoding honour exactly — and
to treat this as the fallback for models and endpoints that cannot.
Extraction is brace-aware rather than regular-expression based, which is the difference that matters: a
pattern that matches from the first { to the last } breaks the moment a string value inside the
object contains a brace, and one that stops at the first } breaks on any nested object. This scanner
tracks string literals and escapes, so a value such as "reason": "use {n} buckets" parses correctly.
Methods
| Method | Summary |
|---|---|
JObject Extract(string response) |
Finds and parses a JSON object in a model reply, or returns null. |
bool TryExtract(string response, JObject json) |
Tries to find and parse a JSON object in a model reply. |
bool TryReadNumber(JObject json, string name, double value) |
Reads a numeric field, accepting a number or a numeric string. |