Documentation
¶
Overview ¶
Package extract provides utilities for extracting structured data (JSON objects, arrays) from text that may contain prose around it.
Common use case: an LLM returns something like
"Sure! Here's the JSON you asked for:
{\"name\": \"alice\", \"age\": 30}
Hope that helps!"
and the caller wants just the {"name": "alice", "age": 30} part. The ExtractJSONObject function performs brace-balanced extraction that handles nested objects, arrays, escaped quotes, and strings.
GrayCode native JSON extraction. Ported to native Go.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Result ¶
Result describes a successful extraction. JSON is the extracted substring (no surrounding prose). Start is the byte offset of the opening brace in the input. End is the byte offset one past the closing brace. Found is true when extraction succeeded.
func ExtractAllJSONObjects ¶
ExtractAllJSONObjects returns every top-level balanced JSON object in s, in source order. Useful when parsing LLM output that may contain several JSON snippets (e.g. a list of objects in prose).
func ExtractJSONArray ¶
ExtractJSONArray is the array counterpart of ExtractJSONObject. It looks for a balanced '[...]' instead of '{...}'.
func ExtractJSONObject ¶
ExtractJSONObject returns the first complete JSON object found in s, or Result{Found: false} if no balanced object exists.
The function:
- Scans for the first '{' that is not inside a string literal.
- Tracks brace depth, supporting nested objects and arrays.
- Skips over string contents (respecting both single and double quotes, with backslash escape sequences).
- Stops when depth returns to zero.
The output preserves the exact bytes from the input (no normalization). If the input is a valid bare JSON object, the output equals the input.