Documentation
¶
Overview ¶
Package jsonrepair repairs malformed JSON strings returned by LLMs, JavaScript snippets, and other JSON-like sources.
Public APIs return errors instead of panicking, and the package does not expose Must* helpers. The only panic-capable paths are package initialization of internal regexp.MustCompile literals, which can fail only if the package source contains an invalid regular expression.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ( // ErrUnexpectedEnd reports that the input ended before the JSON value was complete. ErrUnexpectedEnd = errors.New("unexpected end of json string") // ErrObjectKeyExpected reports that an object key could not be parsed. ErrObjectKeyExpected = errors.New("object key expected") // ErrColonExpected reports that an object key is not followed by a colon. ErrColonExpected = errors.New("colon expected") // ErrInvalidCharacter reports an invalid character inside a JSON string. ErrInvalidCharacter = errors.New("invalid character") // ErrUnexpectedCharacter reports a character that cannot be repaired in context. ErrUnexpectedCharacter = errors.New("unexpected character") // ErrInvalidUnicode reports an invalid Unicode escape sequence. ErrInvalidUnicode = errors.New("invalid unicode character") )
Functions ¶
func Repair ¶ added in v0.2.8
Repair repairs malformed JSON-like input into valid JSON.
It returns a structured *Error when the input is empty or cannot be repaired.
Example ¶
repaired, err := Repair("{name: 'John'}")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(repaired)
Output: {"name": "John"}
Example (Error) ¶
_, err := Repair(`{"a":2}foo`)
if repairErr, ok := errors.AsType[*Error](err); ok {
fmt.Println(repairErr.Message)
fmt.Println(repairErr.Position)
fmt.Println(errors.Is(err, ErrUnexpectedCharacter))
}
Output: unexpected character "f" 7 true
Example (Truncated) ¶
repaired, err := Repair(`{"foo":"bar`)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(repaired)
Output: {"foo":"bar"}
Types ¶
type Error ¶ added in v0.2.3
type Error struct {
// Message describes the repair failure.
Message string
// Position is the rune offset where parsing failed.
Position int
// Err is the underlying sentinel for errors.Is and errors.As.
Err error
}
Error reports a non-repairable parse error and its position.
Click to show internal directories.
Click to hide internal directories.