大模型 json格式 修复

随着大模型应用越来越多,大模型返回的json应用也增多,这些json 时不时会出现破损。 如何修复json串,成为大模型应用要处理的一个问题。

工具

在网上看到这库,试了下效果不错。这是个js库,用typescript写的,可以前端调用;也可以用pythonmonkey 在python 中调用。其原理是BNF解析器,使用解析器的规则修复json格式问题。

安装

js 复制代码
$ npm install jsonrepair

import { jsonrepair } from 'jsonrepair'
try {
const json = "{name: 'John'}"
const repaired = jsonrepair(json)
console.log(repaired) // '{"name": "John"}'
} catch (err) {
console.error(err)
}
python 复制代码
pip install pythonmonkey

import pythonmonkey
jsonrepair = pythonmonkey.require('jsonrepair').jsonrepair
json = "[1,2,3,"
repaired = jsonrepair(json)
print(repaired) 
# [1,2,3]

能修复哪些问题

  • 在缺少的键周围添加引号
  • 添加缺少的转义字符
  • 添加缺失的逗号
  • 添加缺失的右括号
  • 修复截断的 JSON
  • 将单引号替换为双引号
  • "..." 用常规双引号替换特殊引号字符
  • 用常规空格替换特殊空格字符
  • 将 Python 常量NoneTrueFalse替换为nulltruefalse
  • 删除尾随逗号
  • 删除类似/* ... */和的评论// ...
  • 带围栏的代码块,如 ```json和```````````
  • 删除数组和对象中的省略号,例如[1, 2, 3, ...]
  • 删除 JSONP 符号,例如callback({ ... })
  • 从转义字符串中去除转义字符,例如{"stringified": "content"}
  • 删除 MongoDB 数据类型,如NumberLong(2)ISODate("2012-12-19T06:01:17.171Z")
  • 连接字符串,例如"long text" + "more text on next line"
  • 将换行符分隔的 JSON 转换为有效的 JSON 数组,例如:
json 复制代码
{ "id": 1, "name": "John" }
{ "id": 2, "name": "Sarah" } 

网上demo

我测试的情况如下,// 注释,另起一行就可以修复,在同一行的就处理不了。

arduino 复制代码
{
  'firstName': 'John'
  lastName: "Smith"
  fullName: John Smith,
  // 这是一个另  
    scores: [ 7.8 6.3 7.3, ],
  "about": "John loves a challenge, "
// 这是一个另 }

处理有问题:

arduino 复制代码
{
  'firstName': 'John'
  lastName: "Smith"
  fullName: John Smith, // 这是一个另  
    scores: [ 7.8 6.3 7.3, ],
  "about": "John loves a challenge, "
// 这是一个另 }

类似库

相关推荐
莫爷22 分钟前
JSON vs XML vs YAML 深度对比:如何选择合适的数据格式?
xml·前端·json
ZTLJQ9 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
gujunge12 小时前
Spring with AI (4): 搜索扩展——向量数据库与RAG(上)
ai·大模型·llm·openai·qwen·rag·spring ai·deepseek
WitsMakeMen14 小时前
rq-vae训练过程是什么样的
llm
8Qi817 小时前
Hello-Agents阅读笔记--智能体经典范式构建--ReAct
人工智能·笔记·llm·agent·智能体
CoderJia程序员甲20 小时前
GitHub 热榜项目 - 日榜(2026-03-23)
ai·大模型·llm·github·ai教程
bryant_meng20 小时前
【Hung-yi Lee】《Introduction to Generative Artificial Intelligence》(4)
人工智能·深度学习·llm·aigc·业界资讯
CSharp精选营21 小时前
.NET对象转JSON,到底有几种方式?
c#·json·.net·newtonsoft·对象转换·utf8json
淼_@淼21 小时前
python-json
前端·python·json
swipe21 小时前
做 RAG 不能只会检索:为什么 Loader 和 Splitter 才是知识库入库的第一步
算法·llm·agent