Package Exports
- json-llm
Readme
json-llm
🌟 The most comprehensive JSON validation and correction library for handling LLM outputs
json-llm 是一个专门为处理大语言模型(LLM)输出而设计的 JSON 解析和修复库。它能智能处理各种非标准 JSON 格式,包括 Markdown 包裹、单引号、特殊字符、截断等常见问题。
✨ 特性
- 🔧 智能修复 - 自动修复各种 JSON 格式问题
- 📦 Markdown 支持 - 处理代码块包裹的 JSON
- 🔍 智能提取 - 从混合文本中提取 JSON
- 🛡️ 容错机制 - 处理截断、错误响应等异常情况
- 🎯 TypeScript 支持 - 完整的类型定义
- 🚀 零依赖 - 轻量级,无第三方依赖
- 📊 Schema 验证 - 支持 JSON Schema 验证
📦 安装
npm install json-llmyarn add json-llmpnpm add json-llm🚀 快速开始
基础用法
import { parse, safeParse, extract, fix } from 'json-llm';
// 解析 LLM 输出
const llmOutput = `
Here's the data you requested:
\`\`\`json
{
"name": "John",
"age": 30
}
\`\`\`
`;
const result = parse(llmOutput);
console.log(result.data);
// { name: "John", age: 30 }处理常见问题
1. Markdown 代码块
import { parse } from 'json-llm';
const input = '```json\n{"key": "value"}\n```';
const result = parse(input);
// { key: "value" }2. 单引号问题
import { parse } from 'json-llm';
const input = "{'name': 'test', 'value': 123}";
const result = parse(input);
// { name: "test", value: 123 }3. 尾随逗号
import { parse } from 'json-llm';
const input = '{"items": [1, 2, 3,], "count": 3,}';
const result = parse(input);
// { items: [1, 2, 3], count: 3 }4. 注释
import { parse } from 'json-llm';
const input = `{
"name": "test", // 用户名
"value": 123 /* 数值 */
}`;
const result = parse(input);
// { name: "test", value: 123 }5. 未引用的键
import { parse } from 'json-llm';
const input = '{name: "test", age: 25}';
const result = parse(input);
// { name: "test", age: 25 }6. 混合内容提取
import { parse, extract } from 'json-llm';
const input = 'The result is: {"status": "ok"} and more text';
const result = parse(input);
// { status: "ok" }
// 提取所有 JSON
const allJsons = extract(input);
// [{ status: "ok" }]7. 截断的 JSON
import { parse } from 'json-llm';
const input = '{"name": "test", "items": [1, 2';
const result = parse(input);
// { name: "test", items: [1, 2] }📖 API 文档
parse<T>(input, options?)
解析并修复 JSON 字符串。
import { parse } from 'json-llm';
const result = parse('{"key": "value"}', {
repair: true, // 自动修复(默认 true)
extract: true, // 提取 JSON(默认 true)
strict: false, // 宽松模式(默认 false)
defaultValue: null, // 失败时的默认值
onError: 'return-null', // 错误处理策略
});
// 返回值
interface ParseResult<T> {
data: T | null; // 解析后的数据
error: Error | null; // 错误信息
warnings: string[]; // 警告信息
raw: string; // 原始输入
repaired: boolean; // 是否进行了修复
extractedFrom: string | null; // 提取来源
}safeParse<T>(input, options?)
安全解析,永不抛出异常。
import { safeParse } from 'json-llm';
const { data, error, warnings } = safeParse('invalid json');
// data: null, error: Error, warnings: [...]parseOrThrow<T>(input, options?)
解析失败时抛出异常。
import { parseOrThrow } from 'json-llm';
try {
const data = parseOrThrow('invalid json');
} catch (error) {
console.error('Parse failed:', error);
}parseOrDefault<T>(input, defaultValue, options?)
解析失败时返回默认值。
import { parseOrDefault } from 'json-llm';
const data = parseOrDefault('invalid', { fallback: true });
// { fallback: true }extract(input)
从文本中提取所有 JSON。
import { extract } from 'json-llm';
const text = 'First: {"a": 1} Second: {"b": 2}';
const { jsons, positions } = extract(text);
// jsons: [{ a: 1 }, { b: 2 }]fix(input)
修复 JSON 字符串。
import { fix } from 'json-llm';
const result = fix("{'key': 'value',}");
// result.fixed: '{"key":"value"}'
// result.changes: [{ type: 'quote', description: '...' }]validate(data, schema?)
验证 JSON 数据。
import { validate } from 'json-llm';
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name']
};
const result = validate({ name: 'John', age: 30 }, schema);
// { valid: true, errors: [], warnings: [] }detect(input)
检测 JSON 问题。
import { detect } from 'json-llm';
const result = detect("{'key': 'value',}");
// {
// hasJson: true,
// issues: [
// { type: 'single-quotes', severity: 'error', fixable: true },
// { type: 'trailing-comma', severity: 'error', fixable: true }
// ],
// canRepair: true
// }🎯 支持的问题类型
| 问题类型 | 描述 | 示例 |
|---|---|---|
markdown-wrapper |
Markdown 代码块包裹 | ```json\n{...}\n``` |
single-quotes |
使用单引号 | {'key': 'value'} |
unquoted-keys |
键名未加引号 | {name: "value"} |
trailing-comma |
尾随逗号 | [1, 2, 3,] |
comments |
JSON 注释 | {/* comment */} |
unescaped-chars |
未转义的特殊字符 | {"text": "line1\nline2"} |
truncated |
截断的 JSON | {"key": "val |
multiple-json |
多个 JSON 拼接 | {...}{...} |
mixed-content |
混合文本内容 | Text {...} more text |
🔧 工具函数
import {
isObject,
isArray,
deepClone,
deepEqual,
flattenObject,
unflattenObject,
getValueByPath,
setValueByPath,
removeUndefined,
removeNulls,
mergeDeep,
prettyPrint,
minify,
} from 'json-llm';
// 深度克隆
const cloned = deepClone(original);
// 深度比较
const equal = deepEqual(obj1, obj2);
// 扁平化对象
const flat = flattenObject({ a: { b: { c: 1 } } });
// { 'a.b.c': 1 }
// 获取路径值
const value = getValueByPath(data, 'user.profile.name');
// 设置路径值
setValueByPath(data, 'user.profile.name', 'John');
// 美化输出
const pretty = prettyPrint(data, 2);📊 真实场景示例
OpenAI ChatGPT 响应
import { parse } from 'json-llm';
const chatgptResponse = `
Sure! Here's the JSON you requested:
\`\`\`json
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
],
"total": 2
}
\`\`\`
Let me know if you need anything else!
`;
const result = parse(chatgptResponse);
// { users: [...], total: 2 }Anthropic Claude 响应
import { parse } from 'json-llm';
const claudeResponse = `
Based on your request, here's the structured data:
{
"status": "success",
"data": {
"items": ["a", "b", "c"]
}
}
I've formatted this as requested.
`;
const result = parse(claudeResponse);
// { status: "success", data: { items: [...] } }Function Calling 响应
import { parse } from 'json-llm';
const functionCall = `{
"function": "get_weather",
"arguments": {
"location": "San Francisco",
"unit": "celsius"
}
}`;
const result = parse(functionCall);
// { function: "get_weather", arguments: {...} }🤝 对比其他库
| 特性 | json-llm | json-repair | JSON.parse() |
|---|---|---|---|
| Markdown 支持 | ✅ | ❌ | ❌ |
| 单引号修复 | ✅ | ✅ | ❌ |
| 注释移除 | ✅ | ❌ | ❌ |
| 混合内容提取 | ✅ | ❌ | ❌ |
| 截断修复 | ✅ | 部分 | ❌ |
| TypeScript 支持 | ✅ | 部分 | ✅ |
| Schema 验证 | ✅ | ❌ | ❌ |
| 零依赖 | ✅ | ❌ | ✅ |
📝 开发
# 安装依赖
npm install
# 运行测试
npm test
# 构建
npm run build
# 类型检查
npm run typecheck📄 License
MIT © 2024
🙏 致谢
感谢所有为这个项目做出贡献的开发者!如果这个项目对你有帮助,请给一个 ⭐️ Star!