jsonrepair

package module
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 7 Imported by: 17

README

jsonrepair

A Go library that repairs malformed JSON and JSON-adjacent text into valid JSON

Features

  • Missing syntax repair: Adds missing quotes, commas, colons, and closing brackets when the intent is clear.
  • Quote normalization: Converts single quotes and smart quotes into valid JSON string quotes.
  • Comment removal: Removes JavaScript-style line and block comments.
  • Wrapper cleanup: Strips Markdown code fences, JSONP callbacks, MongoDB wrappers, and ellipsis placeholders.
  • Literal conversion: Converts Python-style None, True, and False into JSON literals.
  • String recovery: Repairs escaped strings, concatenated strings, and common truncated string input.
  • NDJSON repair: Converts newline-delimited JSON values into one JSON array.

Installation

go get github.com/kaptinlin/jsonrepair

Requires Go 1.26.4+.

Quick Start

package main

import (
    "fmt"
    "log"

    "github.com/kaptinlin/jsonrepair"
)

func main() {
    repaired, err := jsonrepair.Repair("{name: 'John'}")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(repaired)
}

Output:

{"name": "John"}

API

func Repair(text string) (string, error)

Repair returns the repaired JSON document or a structured *jsonrepair.Error when the input cannot be repaired.

repaired, err := jsonrepair.Repair(input)
if err != nil {
    var repairErr *jsonrepair.Error
    if errors.As(err, &repairErr) {
        fmt.Printf("%s at position %d\n", repairErr.Message, repairErr.Position)
    }
}

Sentinel errors support errors.Is:

  • ErrUnexpectedEnd
  • ErrObjectKeyExpected
  • ErrColonExpected
  • ErrInvalidCharacter
  • ErrUnexpectedCharacter
  • ErrInvalidUnicode

Development

task test    # Run tests with race detection
task lint    # Run golangci-lint and go mod tidy check
task         # Run lint and test

Contributing

Contributions are welcome. Open an issue to discuss substantial changes before submitting a pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgements

This library is a Go port of Jos de Jong's JavaScript jsonrepair library.

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

func Repair(text string) (string, error)

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.

func (*Error) Error added in v0.2.3

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap added in v0.2.3

func (e *Error) Unwrap() error

Unwrap returns the underlying error for errors.Is/As support.

Directories

Path Synopsis
Package main demonstrates usage of the jsonrepair library.
Package main demonstrates usage of the jsonrepair library.

Jump to

Keyboard shortcuts

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