Skip to content

一个用于修复无效 JSON 字符串的 Go 库,特别适用于处理大语言模型(LLM)输出的有问题的 JSON 数据。

License

Notifications You must be signed in to change notification settings

lxw665/json_repair_go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JSON Repair Go

Go Version License: MIT Go Report Card PkgGoDev

Repair invalid JSON strings in Go. Especially handy for cleaning up JSON coming from Large Language Models (LLMs) or hand-written configs.

English | 中文

Features

  • Fix missing/wrong quotes on keys and strings
  • Convert single quotes to double quotes
  • Add missing commas, closing braces/brackets
  • Remove trailing commas
  • Normalize booleans (True/Falsetrue/false) and nulls (Nonenull)
  • Strip comments (//, /* */, #)
  • Light escaping and number parsing fixes
  • Zero external deps (stdlib only)

Install

go get github.com/lxw665/json_repair_go

Note: make sure your import path matches the repository path you publish under. If you fork, replace lxw665 with your GitHub username.

Quick start

package main

import (
    "fmt"
    "log"
    jsonrepair "github.com/lxw665/json_repair_go"
)

func main() {
    broken := `{name: 'John', age: 30, active: True`

    // 1) Repair to JSON string
    fixed, err := jsonrepair.RepairJSON(broken)
    if err != nil { log.Fatal(err) }
    fmt.Println(fixed) // {"name":"John","age":30,"active":true}

    // 2) Parse directly to Go value
    v, err := jsonrepair.Loads(broken)
    if err != nil { log.Fatal(err) }
    fmt.Printf("%+v\n", v)
}

API

  • RepairJSON(jsonStr string) (string, error) — Repair and return a JSON string
  • RepairJSONWithOptions(jsonStr string, options RepairOptions) (string, error)
  • Loads(jsonStr string) (interface{}, error) — Repair and parse to Go values
  • Unmarshal(data []byte, v any) error — Drop-in for json.Unmarshal with repair
  • Load(r io.Reader, v any) error

Options:

type RepairOptions struct {
    SkipValidation bool // Skip initial json.Unmarshal check
    ReturnObjects  bool // Return parsed objects instead of JSON string
    Logging        bool // Enable repair logs
    StreamStable   bool // Keep repair stable for streaming use-cases
    EnsureASCII    bool // Escape non-ASCII
}

Examples

Input ➜ Output

  • {name: 'John', age: 30{"name":"John","age":30}
  • {'key': 'value',}{"key":"value"}
  • [1, 2, 3,[1,2,3]
  • {"active": True}{"active":true}
  • {"value": None}{"value":null}
  • {a: 1, b: 2{"a":1,"b":2}

More runnable examples in demo/:

cd demo
go run .

Testing

go test -v
go test -bench=.
go test -cover

Related work

Contributing

PRs and issues are welcome.

  1. Fork ➜ 2) create branch ➜ 3) commit ➜ 4) push ➜ 5) open PR

License

MIT. See LICENSE.


If this project helps you, please give it a ⭐️!

About

一个用于修复无效 JSON 字符串的 Go 库,特别适用于处理大语言模型(LLM)输出的有问题的 JSON 数据。

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages