llmjsonrepair
Repairs malformed or truncated JSON from large language models
About llmjsonrepair
llmjsonrepair
30-second quickstart · 30 秒上手
Go library for salvaging malformed LLM JSON when retrying is not an option. 当模型输出的 JSON 被截断、又不方便重试时,可以用这个 Go 库尝试修复。
Try it in Go Playground / 在线试用 (no installation needed).
Requires Go 1.24+. In an existing Go module (run go mod init demo first if needed):
go get github.com/qdxiao/llmjsonrepair/pkg
Save as main.go in a demo module and run go run .:
package main
import (
"fmt"
"log"
repair "github.com/qdxiao/llmjsonrepair/pkg"
)
func main() {
fixed, err := repair.Repair(`{"items":["a","b"`)
if err != nil {
log.Fatal(err)
}
fmt.Println(fixed)
}
The output is formatted JSON equivalent to {"items":["a","b"]}.
Use Repair for JSON text or Loads for parsed Go values.
What repair cannot recover · 修复的边界
- A missing value is not recoverable. For example,
{"total":repairs to{"total":null}. - Strip known framing before repair if you expect a single object. For example,
Here is the JSON: {"ok":truerepairs to["the JSON",{"ok":true}], not an object. - Validate the expected shape, required fields, and values after repair. Retry the upstream request when required data is missing or when a guess would be unsafe.
修复只能尽量补齐结构,不能恢复未生成的值。若预期单个对象,先去掉已知前缀;修复后校验根类型、必填字段和值,关键数据缺失时重试。
Required numbers: A plain int in a fresh Go struct stays 0 after decoding either null or an absent field. For a required total, decode into a fresh struct with Total *int (tagged json:"total"). Check the json.Unmarshal error first, then reject Total == nil. An explicit 0 gives a non-nil pointer to zero.
必填数字: 用 Go 的 json.Unmarshal 解码到新建结构体时,字段为 null 或不存在都会让普通 int 保持为 0。若 total 必填,请用 Total *int(标签为 json:"total"),先检查解码错误,再拒绝 Total == nil。显式传入的 0 会得到指向零的非空指针。
中文
专门用于修复大模型输出 JSON 格式错误的 Go 语言库
简介
llmjsonrepair 是一个强大的 Go 语言库,专门用于修复大语言模型(LLM)输出的不完整或格式错误的 JSON 数据。当 LLM 生成的 JSON 因为各种原因(如输出截断、格式错误、缺少引号等)无法正常解析时,这个库可以智能地修复这些问题。
特性
- 🔧 智能修复: 自动修复各种 JSON 格式错误
- 🎯 上下文感知: 基于解析上下文智能推断缺失的结构
- 🚀 高容错性: 处理深度嵌套、混合格式等复杂情况
- 📦 简单易用: 提供简洁的 API 接口
- 🔄 多对象支持: 支持处理连续的 JSON 对象流
- 🧠 LLM 友好: 专门针对大模型输出特点设计
支持修复的问题类型
- ✅ 缺少结尾括号/方括号
- ✅ 对象键缺少引号
- ✅ 字符串未正确闭合
- ✅ 深度嵌套结构错误
- ✅ 混乱的引号和转义字符
- ✅ 多 JSON 对象流被截断
- ✅ 缺少分隔符(逗号、冒号)
- ⚠️ 包含 JSON 之外的说明文字时,结果可能不是单个对象;见上方「修复的边界」
安装
go get github.com/qdxiao/llmjsonrepair/pkg
快速开始
package main
import (
"fmt"
"log"
"github.com/qdxiao/llmjsonrepair/pkg"
)
func main() {
// 示例:修复缺少结尾括号的 JSON
malformedJSON := `{"name": "John", "age": 30, "skills": ["Go", "Python"`
// 方法1: 修复并返回格式化的 JSON 字符串
repairedJSON, err := pkg.Repair(malformedJSON)
if err != nil {
log.Fatal(err)
}
fmt.Println("修复后的 JSON:")
fmt.Println(repairedJSON)
// 方法2: 修复并返回解析后的数据结构
data, err := pkg.Loads(malformedJSON)
if err != nil {
log.Fatal(err)
}
fmt.Printf("解析后的数据: %+v\n", data)
}
API 文档
Repair(jsonStr string) (string, error)
修复 JSON 字符串并返回格式化的 JSON 字符串。
参数:
jsonStr: 需要修复的 JSON 字符串
返回:
string: 修复并格式化后的 JSON 字符串error: 错误信息(如果修复失败)
Loads(jsonStr string) (interface{}, error)
修复 JSON 字符串并返回解析后的数据结构。
参数:
jsonStr: 需要修复的 JSON 字符串
返回:
interface{}: 解析后的数据结构(map[string]interface{}或[]interface{})error: 错误信息(如果修复失败)
使用示例
查看 example/main.go 文件获取更多详细的使用示例,包括各种错误类型的修复演示。
贡献
欢迎提交 Issue 和 Pull Request!
许可证
MIT License
English
A Go library specifically designed to repair malformed JSON output from Large Language Models (LLMs)
Introduction
llmjsonrepair is a powerful Go library designed to fix incomplete or malformed JSON data output by Large Language Models (LLMs). When JSON generated by LLMs cannot be parsed normally due to various reasons (such as output truncation, format errors, missing quotes, etc.), this library can intelligently repair these issues.
Features
- 🔧 Smart Repair: Automatically fixes various JSON format errors
- 🎯 Context Aware: Intelligently infers missing structures based on parsing context
- 🚀 High Fault Tolerance: Handles complex situations like deep nesting and mixed formats
- 📦 Easy to Use: Provides clean API interfaces
- 🔄 Multi-Object Support: Supports processing continuous JSON object streams
- 🧠 LLM Friendly: Specifically designed for LLM output characteristics
Supported Error Types
- ✅ Missing closing brackets/braces
- ✅ Object keys without quotes
- ✅ Unclosed strings
- ✅ Deep nested structure errors
- ✅ Messy quotes and escape characters
- ✅ Truncated multi-JSON object streams
- ✅ Missing separators (commas, colons)
- ⚠️ Extra prose can change the result shape; see “What repair cannot recover” above
Installation
go get github.com/qdxiao/llmjsonrepair/pkg
Quick Start
package main
import (
"fmt"
"log"
"github.com/qdxiao/llmjsonrepair/pkg"
)
func main() {
// Example: Fix JSON with missing closing bracket
malformedJSON := `{"name": "John", "age": 30, "skills": ["Go", "Python"`
// Method 1: Repair and return formatted JSON string
repairedJSON, err := pkg.Repair(malformedJSON)
if err != nil {
log.Fatal(err)
}
fmt.Println("Repaired JSON:")
fmt.Println(repairedJSON)
// Method 2: Repair and return parsed data structure
data, err := pkg.Loads(malformedJSON)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Parsed data: %+v\n", data)
}
API Documentation
Repair(jsonStr string) (string, error)
Repairs a JSON string and returns a formatted JSON string.
Parameters:
jsonStr: The JSON string to be repaired
Returns:
string: The repaired and formatted JSON stringerror: Error information (if repair fails)
Loads(jsonStr string) (interface{}, error)
Repairs a JSON string and returns the parsed data structure.
Parameters:
jsonStr: The JSON string to be repaired
Returns:
interface{}: The parsed data structure (map[string]interface{}or[]interface{})error: Error information (if repair fails)
Examples
See the example/main.go file for more detailed usage examples, including demonstrations of repairing various error types.
Contributing
Issues and Pull Requests are welcome!
License
MIT License
Frequently Asked Questions
What is llmjsonrepair?
llmjsonrepair is a JSON library for the Go programming language. Repairs malformed or truncated JSON from large language models
How do I install llmjsonrepair?
Install llmjsonrepair with the Go module system using `go get qdxiao/llmjsonrepair`. Check the repository for the current installation instructions.
What category does llmjsonrepair belong to?
llmjsonrepair is listed under JSON, specifically JSON.