sap

package module
v0.0.0-...-0624e57 Latest Latest
Warning

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

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

README

GSAP - Go Schema-Aligned Parser

CI Go Reference Go Report Card

GSAP - sloppy LLM JSON in, clean Go structs out

A robust JSON parser for Go inspired by BAML's Schema-Aligned Parsing (SAP) algorithm. GSAP handles messy LLM-generated JSON by gracefully recovering from common issues like missing quotes, trailing commas, single quotes, and type mismatches -- so you can focus on your application logic instead of writing JSON cleanup code.

Features

JSON Extraction and Fixing
  • Extract JSON from markdown code blocks, natural language, and chain-of-thought output
  • Fix unquoted keys/values, single/triple quotes, trailing commas, unclosed structures
  • Skip comments (//, /* */)
Smart Type Coercion
  • Strings to numbers: "42"42, "1/5"0.2, "$1,234.56"1234.56
  • Numbers with units: "30 years"30, "$200K"200000, "4 GB"4
  • Markdown stripping: "**42**"42, "_true_"true
  • Booleans: "yes", "no", "on", "off", "y", "n", "enabled", "disabled"
  • Null strings: "N/A", "none", "null", "unknown", "TBD"nil for pointer fields
  • Time parsing: RFC3339, date-only ("2024-01-15"), Unix timestamps
  • Comma-separated strings to slices: "python, go, rust"["python", "go", "rust"]
  • Embedded struct field flattening
Fuzzy String Matching
  • Unicode accent removal (étudeetude) and ligature expansion (æae)
  • Levenshtein distance-based enum value matching and disambiguation
Type-Safe Parsing
  • Generic Parse[T] API -- works with any Go struct
  • Automatic field matching via JSON tags with case-insensitive fallback
  • Score-based best match selection across multiple JSON candidates

Installation

go get github.com/carpcarp/gsap

Quick Start

package main

import (
	"fmt"
	"github.com/carpcarp/gsap"
)

type User struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Email string `json:"email"`
}

func main() {
	// Even with messy input, GSAP parses it correctly
	input := `{name: "Alice", age: "30", email: "alice@example.com"}`

	user, err := gsap.Parse[User](input)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s is %d years old\n", user.Name, user.Age)
	// Output: Alice is 30 years old
}

Real-World LLM Output

Here's what LLM output actually looks like — and what GSAP does with it:

type JobCandidate struct {
    Name       string    `json:"name"`
    Age        int       `json:"age"`
    Email      string    `json:"email"`
    Skills     []string  `json:"skills"`
    Experience int       `json:"experience"`
    Salary     float64   `json:"salary"`
    Remote     bool      `json:"remote"`
    StartDate  time.Time `json:"start_date"`
    Website    *string   `json:"website"`
    Notes      *string   `json:"notes"`
}

Feed this absolute mess to gsap.Parse:

Sure! Here's the candidate information I extracted:

```json
{
    // Personal details
    name: 'Jane Doe',
    'age': "29 years",
    email: 'jane.doe@example.com',

    /* Professional info */
    skills: "go, python, react, typescript",
    experience: "8 years",
    salary: "$185K",
    remote: "yes",
    start_date: "2025-03-15",

    // Optional fields
    website: "N/A",
    notes: "TBD",
}
```

Let me know if you need anything else!
candidate, err := gsap.Parse[JobCandidate](input)

One call. Clean struct:

Field Raw Garbage Parsed Result What GSAP Did
Name name: 'Jane Doe' "Jane Doe" Unquoted key, single-quote value
Age "29 years" 29 Stripped units, string to int
Email email: 'jane.doe@example.com' "jane.doe@example.com" Unquoted key, single quotes
Skills "go, python, react, typescript" ["go", "python", "react", "typescript"] Comma-separated string to slice
Experience "8 years" 8 Stripped units, string to int
Salary "$185K" 185000 Currency symbol, K suffix
Remote "yes" true Boolean coercion
StartDate "2025-03-15" time.Time{2025-03-15} Date string to time.Time
Website "N/A" nil Null string detection
Notes "TBD" nil Null string detection

Plus: extracted JSON from markdown code block, skipped // and /* */ comments, removed trailing commas, and auto-fixed the entire malformed structure.

Usage Examples

Extracting JSON from LLM Output
input := `Here's the user data:
` + "```json" + `
{
  "name": "Charlie",
  "age": 35,
  "email": "charlie@example.com"
}
` + "```"

user, err := gsap.Parse[User](input)
Fixing Malformed JSON
// Unquoted keys, trailing comma, string-typed number
input := `{name: "David", age: "40", email: david@example.com,}`
user, err := gsap.Parse[User](input)
// user.Age == 40 (coerced from string)
Numbers with Units and Markdown

LLMs often wrap values in markdown or append units. GSAP handles both:

type Candidate struct {
	Name       string  `json:"name"`
	Experience int     `json:"experience"`
	Salary     float64 `json:"salary"`
}

input := `{"name": "**Alice**", "experience": "10 years", "salary": "$200K"}`
c, err := gsap.Parse[Candidate](input)
// c.Name == "Alice", c.Experience == 10, c.Salary == 200000
Time Parsing
type Event struct {
	Name string    `json:"name"`
	Date time.Time `json:"date"`
}

input := `{"name": "Launch", "date": "2024-01-15"}`
event, err := gsap.Parse[Event](input)
// event.Date is a time.Time for Jan 15, 2024
Null String Handling

LLMs often use placeholder strings instead of JSON null:

type Profile struct {
	Name    string  `json:"name"`
	Website *string `json:"website"`
}

input := `{"name": "Bob", "website": "N/A"}`
p, err := gsap.Parse[Profile](input)
// p.Website == nil (recognized as null)
Comma-Separated Strings to Slices
type Developer struct {
	Name   string   `json:"name"`
	Skills []string `json:"skills"`
}

input := `{"name": "Eve", "skills": "python, go, rust"}`
dev, err := gsap.Parse[Developer](input)
// dev.Skills == []string{"python", "go", "rust"}
Parse Quality Scoring
user, score, err := gsap.ParseWithScore[User](input)
if score != nil {
	fmt.Printf("Parse score: %d (lower is better)\n", score.Total())
	fmt.Printf("Coercions applied: %v\n", score.Flags())
}
Manual JSON Fixing
messy := `{name: John, age: 30,}`  // Unquoted, trailing comma
fixed, err := gsap.FixJSON(messy)
// fixed: `{"name": "John", "age": 30}`

How It Works

1. JSON Extraction

GSAP first extracts potential JSON from the input text:

  1. Try standard JSON parsing
  2. Look for markdown code blocks (```json ... ```)
  3. Find balanced JSON objects/arrays in text
  4. Fall back to fixing malformed JSON
2. JSON Fixing

When JSON is malformed, GSAP's fixing parser:

  • Tracks open/close brackets and quotes
  • Automatically quotes unquoted keys/values
  • Converts single/triple quotes to double quotes
  • Removes comments and trailing commas
  • Auto-closes incomplete structures
3. Type Coercion

After getting valid JSON, GSAP coerces values to match the target type:

  • String "42" → int 42, "$200K" → float 200000
  • String "true", "yes", "enabled" → bool true
  • Float 3.7 → int 4 (rounds)
  • "1/5" → float 0.2
  • "2024-01-15"time.Time
  • "N/A"nil for pointer fields
  • "a, b, c"[]string{"a", "b", "c"}
  • Strips markdown: "**42**"42
  • Fuzzy matches enum values
4. Best Match Selection

When multiple parsings are valid, GSAP picks the best using a scoring system:

  • Exact matches score lowest (best)
  • Type coercions score higher
  • Fuzzy matches score highest (worst)

Configuration

Strict Mode (No Fixing)
parser := gsap.NewParser().WithStrict(true)
result, _, _ := parser.ParseWithScore(input, reflect.TypeOf(User{}))
Incomplete JSON for Streaming
parser := gsap.NewParser().WithIncompleteJSON(true)
// Allows parsing of incomplete JSON for streaming responses

Integration with instructor-go

GSAP can be used as a drop-in JSON unmarshaler for instructor-go:

import (
	"reflect"
	"github.com/carpcarp/gsap"
)

// GsapUnmarshaler wraps GSAP as a JSON unmarshaler
type GsapUnmarshaler struct{}

func (u *GsapUnmarshaler) Unmarshal(data []byte, v any) error {
	parser := gsap.NewParser()
	result, err := parser.Parse(string(data), reflect.TypeOf(v).Elem())
	if err != nil {
		return err
	}
	reflect.ValueOf(v).Elem().Set(reflect.ValueOf(result))
	return nil
}

Performance

  • Extraction: O(n) single pass through input text
  • Fixing: O(n) state machine
  • Coercion: O(m) where m is number of struct fields
  • Overall: Near-linear performance for typical LLM outputs

Comparison to BAML

Feature GSAP BAML
JSON fixing
Type coercion
Fuzzy matching
time.Time parsing
Null string detection
Markdown stripping
Language Go (native) Rust (generates Go)
Schema DSL ❌ (uses structs)
Streaming support Partial
Type safety ✅ (generics)

Testing

go test -v -race ./...
go test -bench=. -benchmem ./...

Roadmap

v0.2 (Current)
  • time.Time support (RFC3339, date-only, Unix timestamps)
  • Null string handling ("N/A", "none", "null" → nil)
  • Comma-separated string → slice conversion
  • Markdown formatting stripping from values
  • Numbers with units ("30 years", "$200K")
  • Embedded struct support
  • Extended boolean variants ("y"/"n", "enabled"/"disabled")
  • Exported score flag constants
  • Score.Flags() introspection API
v0.3
  • io.Reader streaming for incremental parsing
  • json.Unmarshaler / encoding.TextUnmarshaler detection
  • Options/Builder pattern for parser configuration
  • Reflection caching for repeated type parsing
v0.4+
  • Drop-in adapters for OpenAI, Anthropic, and LangChain Go SDKs
  • JSON Schema validation and generation
  • Structured error types with per-field context
  • Union type support
  • Constraint validation

Contributing

PRs welcome! See CONTRIBUTING.md for guidelines.

Focus areas:

  • Streaming / io.Reader support
  • SDK adapter implementations
  • Performance optimizations

License

MIT

Acknowledgments

Inspired by BAML's Schema-Aligned Parsing algorithm. GSAP extracts this powerful parsing capability into a lightweight, pure-Go library for use with any Go LLM client.

Documentation

Overview

Package sap provides a Schema-Aligned Parser for extracting typed data from messy LLM-generated JSON.

LLMs frequently produce JSON that is technically invalid: wrapped in markdown code blocks, decorated with explanatory text, or containing syntax errors like unquoted keys, single quotes, trailing commas, and inline comments. Package sap handles all of this automatically. It extracts JSON candidates from free-form text, fixes common formatting problems, coerces mismatched types to fit your target struct, and picks the best parse result via a scoring system.

Quick Start

The simplest way to use sap is the generic Parse function:

type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

user, err := sap.Parse[User](llmResponse)

If you need to inspect how much coercion was required, use ParseWithScore. Lower scores indicate cleaner parses:

user, score, err := sap.ParseWithScore[User](llmResponse)
fmt.Printf("parse quality score: %d\n", score.Total())

To fix malformed JSON without parsing it into a struct, use FixJSON directly:

fixed, err := sap.FixJSON(`{name: 'Alice', age: 30,}`)
// fixed is now valid JSON: {"name": "Alice", "age": 30}

JSON Extraction

When the input is not already valid JSON, the extractor runs through several strategies in order:

  1. Try parsing the trimmed input as standard JSON.
  2. Look for JSON inside markdown code blocks (```json ... ```).
  3. Scan the text for balanced { } and [ ] blocks.
  4. Attempt to fix any candidate that fails standard parsing by quoting unquoted keys, converting single quotes and backticks to double quotes, removing trailing commas, and stripping comments.

The best candidate is selected by parsing each one against your target type and comparing scores.

Type Coercion

The type coercer transforms JSON values to fit your Go struct fields. Supported coercions include:

  • String to int/float: "42" becomes 42, "$1,234.56" becomes 1234.56
  • String to bool: "true", "yes", "1", "on" become true; "false", "no", "0", "off" become false
  • Fractions: "1/5" becomes 0.2
  • Currency: "$1,000" becomes 1000
  • Number to bool: 0 is false, nonzero is true
  • Bool to int: true is 1, false is 0
  • Case-insensitive struct field matching
  • Fuzzy enum matching with Unicode normalization

Each coercion adds a penalty to the parse score so you can distinguish a clean parse from one that required significant transformation.

Streaming

For streaming LLM responses, ParsePartial accepts incomplete JSON and reports a CompletionState (Complete, Incomplete, or Pending):

user, state, err := sap.ParsePartial[User](partialResponse)

instructor-go Integration

To use sap as the parser for instructor-go, create an InstructorParser:

parser := sap.NewInstructorParser()
client := instructor.FromOpenAI(openaiClient,
    instructor.WithParser(parser),
)

The InstructorParser implements the instructor-go Parser interface, replacing its default JSON unmarshaling with the full sap extraction and coercion pipeline.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultParser = NewParser()

DefaultParser is the default SAP parser instance

Functions

func CoerceToEnum

func CoerceToEnum(value interface{}, enumType reflect.Type, score *Score) (interface{}, error)

CoerceToEnum attempts to coerce a value to an enum type

func FixJSON

func FixJSON(input string) (string, error)

FixJSON attempts to fix malformed JSON

Example
input := `{name: "Alice", age: 30, email: "alice@example.com",}`

fixed, err := FixJSON(input)
if err != nil {
	panic(err)
}

// The fixed JSON can now be parsed by encoding/json
user, err := Parse[TestUser](fixed)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
Output:
Alice
30
Example (Comments)
input := `{
		// Name of the user
		"name": "Grace",
		/* Age in years */ "age": 31,
		"email": "grace@example.com"
	}`

fixed, err := FixJSON(input)
if err != nil {
	panic(err)
}

// Comments are removed, valid JSON remains
user, err := Parse[TestUser](fixed)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
Output:
Grace
31
Example (SingleQuotes)
input := `{'name': 'David', 'age': 40, 'email': 'david@example.com'}`

fixed, err := FixJSON(input)
if err != nil {
	panic(err)
}

user, err := Parse[TestUser](fixed)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
Output:
David
40

func NewParser

func NewParser() *sapParser

NewParser creates a new SAP parser with default options

Example
// Create a custom parser with strict mode enabled.
// Strict mode rejects malformed JSON instead of fixing it.
userType := reflect.TypeOf(TestUser{})

// Valid JSON works fine in strict mode
parser := NewParser().WithStrict(true)
validInput := `{"name": "Alice", "age": 30, "email": "alice@example.com"}`
_, err := parser.Parse(validInput, userType)

// Unquoted keys are rejected in strict mode
invalidInput := `{name: "Alice", age: 30}`
_, err2 := NewParser().WithStrict(true).Parse(invalidInput, userType)

fmt.Printf("valid input error: %v\n", err)
fmt.Printf("invalid input rejected: %v\n", err2 != nil)
Output:
valid input error: <nil>
invalid input rejected: true

func Parse

func Parse[T any](input string) (T, error)

Parse parses input text into the target type This is the main public API

Example
input := `{"name": "Alice", "age": 30, "email": "alice@example.com"}`

user, err := Parse[TestUser](input)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
fmt.Println(user.Email)
Output:
Alice
30
alice@example.com
Example (BooleanCoercion)
// SAP coerces string "yes" to bool true
input := `{"title": "Dev", "experience": ["Go"], "active": "yes"}`

resume, err := Parse[TestResume](input)
if err != nil {
	panic(err)
}

fmt.Println(resume.Title)
fmt.Println(resume.Active)
Output:
Dev
true
Example (ChainOfThought)
input := `Let me extract the user info:
The user's name is Alice and they are 30 years old.

Here's the structured data:
{
  "name": "Alice",
  "age": 30,
  "email": "alice@example.com"
}

Hope this helps!`

user, err := Parse[TestUser](input)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
fmt.Println(user.Email)
Output:
Alice
30
alice@example.com
Example (ComplexTypes)
input := `{"title": "Engineer", "experience": ["Go", "Rust", "Python"], "active": true}`

resume, err := Parse[TestResume](input)
if err != nil {
	panic(err)
}

fmt.Println(resume.Title)
fmt.Println(len(resume.Experience))
fmt.Println(resume.Experience[0])
fmt.Println(resume.Active)
Output:
Engineer
3
Go
true
Example (Markdown)
input := "Here's the user data:\n```json\n{\"name\": \"Bob\", \"age\": 25, \"email\": \"bob@example.com\"}\n```"

user, err := Parse[TestUser](input)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
Output:
Bob
25
Example (RealWorldLLMOutput)
// This is what LLM output actually looks like — chain-of-thought preamble,
// markdown code block, broken JSON with comments, mixed quotes, and values
// that need coercion. GSAP handles all of it in a single call.
input := "Sure! Here's the candidate information I extracted:\n\n" +
	"```json\n" +
	"{\n" +
	"    // Personal details\n" +
	"    name: 'Jane Doe',\n" +
	"    'age': \"29 years\",\n" +
	"    email: 'jane.doe@example.com',\n" +
	"\n" +
	"    /* Professional info */\n" +
	"    skills: \"go, python, react, typescript\",\n" +
	"    experience: \"8 years\",\n" +
	"    salary: \"$185K\",\n" +
	"    remote: \"yes\",\n" +
	"    start_date: \"2025-03-15\",\n" +
	"\n" +
	"    // Optional fields\n" +
	"    website: \"N/A\",\n" +
	"    notes: \"TBD\",\n" +
	"}\n" +
	"```\n\n" +
	"Let me know if you need anything else!"

candidate, err := Parse[TestCandidate](input)
if err != nil {
	panic(err)
}

fmt.Println(candidate.Name)
fmt.Println(candidate.Age)
fmt.Println(candidate.Email)
fmt.Println(candidate.Skills)
fmt.Println(candidate.Experience)
fmt.Println(candidate.Salary)
fmt.Println(candidate.Remote)
fmt.Println(candidate.StartDate.Format("2006-01-02"))
fmt.Println(candidate.Website)
fmt.Println(candidate.Notes)
Output:
Jane Doe
29
jane.doe@example.com
[go python react typescript]
8
185000
true
2025-03-15
<nil>
<nil>
Example (TypeCoercion)
// SAP coerces string "30" to int 30 automatically
input := `{"name": "Alice", "age": "30", "email": "alice@example.com"}`

user, err := Parse[TestUser](input)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
Output:
Alice
30

Types

type Coercer

type Coercer interface {
	// Coerce transforms a value to match the target type
	Coerce(value interface{}, targetType reflect.Type) (interface{}, *Score, error)
}

Coercer defines the interface for type coercion

type CompletionState

type CompletionState int

CompletionState represents the parsing completion status

const (
	// Complete means all required fields are present
	Complete CompletionState = iota
	// Incomplete means some required fields are missing (for streaming)
	Incomplete
	// Pending means parsing is ongoing
	Pending
)

func ParsePartial

func ParsePartial[T any](input string) (T, CompletionState, error)

ParsePartial parses input as a partial type (for streaming)

type EnumCoercer

type EnumCoercer struct{}

EnumCoercer handles coercion to enum types

type Extractor

type Extractor struct {
	// contains filtered or unexported fields
}

Extractor handles JSON extraction from text

func NewExtractor

func NewExtractor(opts *ParseOptions) *Extractor

NewExtractor creates a new JSON extractor

func (*Extractor) ExtractJSON

func (e *Extractor) ExtractJSON(input string) ([]JSONCandidate, error)

ExtractJSON extracts potential JSON from text Returns candidates in order of likelihood

type FixingParser

type FixingParser struct {
	// contains filtered or unexported fields
}

FixingParser handles malformed JSON

type InstructorParser

type InstructorParser struct {
	// contains filtered or unexported fields
}

InstructorParser wraps SAP for use with instructor-go This allows you to use SAP as a custom parser for instructor-go

Example usage:

import (
    "github.com/567-labs/instructor-go/pkg/instructor"
    "github.com/alcarpenter/gsap"
)

// Create a SAP-based parser
parser := sap.NewInstructorParser()

// Use with instructor-go
client := instructor.FromOpenAI(openaiClient,
    instructor.WithParser(parser),
)

func NewInstructorParser

func NewInstructorParser() *InstructorParser

NewInstructorParser creates a new instructor-go compatible parser using SAP

Example
// NewInstructorParser creates a parser compatible with instructor-go.
// Use it as a drop-in custom parser for instructor-go clients.
parser := NewInstructorParser()

// The parser implements Unmarshal([]byte, interface{}) error
var user TestUser
err := parser.Unmarshal(
	[]byte(`{"name": "Alice", "age": "30", "email": "alice@example.com"}`),
	&user,
)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
Output:
Alice
30

func (*InstructorParser) Unmarshal

func (ip *InstructorParser) Unmarshal(data []byte, v interface{}) error

Unmarshal implements the instructor-go Parser interface It takes the LLM response and parses it into the target type

func (*InstructorParser) WithIncompleteJSON

func (ip *InstructorParser) WithIncompleteJSON(allow bool) *InstructorParser

WithIncompleteJSON allows incomplete JSON for streaming

func (*InstructorParser) WithStrict

func (ip *InstructorParser) WithStrict(strict bool) *InstructorParser

WithStrict creates a new parser in strict mode

type JSONCandidate

type JSONCandidate struct {
	JSON  string // The JSON string
	Index int    // Starting position in original text
}

JSONCandidate represents a potential JSON string extracted from text

type ParseOptions

type ParseOptions struct {
	Streaming StreamingOptions
	Strict    bool // If true, only accept exact JSON matches
}

ParseOptions configures parsing behavior

type ParseResult

type ParseResult struct {
	Value            interface{}
	Score            *Score
	CompletionState  CompletionState
	RemainingContent string // Text that wasn't part of JSON
}

ParseResult represents a successful parse

type Parser

type Parser interface {
	// Parse extracts potential JSON candidates from input text
	Parse(input string) ([]JSONCandidate, error)
}

Parser defines the interface for extracting JSON from text

type Score

type Score struct {
	// contains filtered or unexported fields
}

Score represents the quality of a parse result Lower scores are better

func ParseWithScore

func ParseWithScore[T any](input string) (T, *Score, error)

ParseWithScore is like Parse but also returns the parse score

Example
// ParseWithScore returns a quality score alongside the result.
// Lower scores indicate cleaner input (fewer fixes needed).
input := `{"name": "Frank", "age": "50", "email": "frank@example.com"}`

user, score, err := ParseWithScore[TestUser](input)
if err != nil {
	panic(err)
}

fmt.Println(user.Name)
fmt.Println(user.Age)
fmt.Printf("score >= 0: %v\n", score.Total() >= 0)
Output:
Frank
50
score >= 0: true

func (*Score) AddFlag

func (s *Score) AddFlag(flag string, value int)

Flag adds to the score

func (*Score) Flags

func (s *Score) Flags() map[string]int

Flags returns a copy of the score flags and their values.

func (*Score) Less

func (s *Score) Less(other *Score) bool

Less returns true if this score is better than other

func (*Score) Total

func (s *Score) Total() int

Total returns the total score

type ScoreFlag

type ScoreFlag = string

ScoreFlag represents a type of coercion or transformation applied during parsing.

const (
	FlagFloatToInt          ScoreFlag = "FloatToInt"
	FlagStringToInt         ScoreFlag = "StringToInt"
	FlagBoolToInt           ScoreFlag = "BoolToInt"
	FlagStringToFloat       ScoreFlag = "StringToFloat"
	FlagStringToBool        ScoreFlag = "StringToBool"
	FlagNumberToBool        ScoreFlag = "NumberToBool"
	FlagFuzzyFieldMatch     ScoreFlag = "FuzzyFieldMatch"
	FlagEnumCaseInsensitive ScoreFlag = "EnumCaseInsensitive"
	FlagEnumFuzzyMatch      ScoreFlag = "EnumFuzzyMatch"
	FlagStringToTime        ScoreFlag = "StringToTime"
	FlagUnixToTime          ScoreFlag = "UnixToTime"
	FlagMarkdownStripped    ScoreFlag = "MarkdownStripped"
	FlagUnitStripped        ScoreFlag = "UnitStripped"
	FlagMultiplierApplied   ScoreFlag = "MultiplierApplied"
	FlagNullStringCoerced   ScoreFlag = "NullStringCoerced"
	FlagCommaSplitToSlice   ScoreFlag = "CommaSplitToSlice"
	FlagEmbeddedStruct      ScoreFlag = "EmbeddedStruct"
)

type StreamingOptions

type StreamingOptions struct {
	AllowIncompleteJSON  bool
	TrackCompletionState bool
}

StreamingOptions configures streaming behavior

type TypeCoercer

type TypeCoercer struct {
	// contains filtered or unexported fields
}

TypeCoercer handles type coercion

func NewTypeCoercer

func NewTypeCoercer() *TypeCoercer

NewTypeCoercer creates a new type coercer

func (*TypeCoercer) Coerce

func (c *TypeCoercer) Coerce(value interface{}, targetType reflect.Type) (interface{}, *Score, error)

Coerce transforms a value to match the target type

Jump to

Keyboard shortcuts

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