extract

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 0 Imported by: 0

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

type Result struct {
	JSON  string
	Start int
	End   int
	Found bool
}

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

func ExtractAllJSONObjects(s string) []Result

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

func ExtractJSONArray(s string) Result

ExtractJSONArray is the array counterpart of ExtractJSONObject. It looks for a balanced '[...]' instead of '{...}'.

func ExtractJSONObject

func ExtractJSONObject(s string) Result

ExtractJSONObject returns the first complete JSON object found in s, or Result{Found: false} if no balanced object exists.

The function:

  1. Scans for the first '{' that is not inside a string literal.
  2. Tracks brace depth, supporting nested objects and arrays.
  3. Skips over string contents (respecting both single and double quotes, with backslash escape sequences).
  4. 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL