优秀的编程知识分享平台

网站首页 > 技术文章 正文

99% 的人都遇到的 JSON 错误, jsonrepair 修复一气呵成!

nanyue 2025-09-06 08:56:20 技术文章 1 ℃

家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力。

1. 什么是 jsonrepair

jsonrepair 是用于修复无效 JSON 文档的工具,其可以自动修复以下问题:

  • 在键周围添加缺失的引号、缺失的转义符、缺失的逗号、缺失的右括号
  • 修复截断的 JSON,用双引号替换单引号,用普通双引号替换特殊引号字符,例如: ...
  • 用普通空格替换特殊空格、用 null、true 和 false 替换 Python 常量 None、True 和 False
  • 删除尾随逗号和注释,例如: /* ... */ 和 // ...
  • 删除带分隔符的代码块(例如 json 和
  • 删除数组和对象中的省略号,例如: [1, 2, 3, ...]
  • 删除 JSONP 表示法,例如: callback({...})
  • 从转义字符串,例如: {"stringified": "content"}
  • 删除 MongoDB 数据类型,例如: NumberLong(2) 和 ISODate("2012-12-19T06:01:17.171Z")
  • 连接字符串,例如: “长文本”+“下一行有更多文本”
  • 将换行符分隔的 JSON 转换为有效的 JSON 数组,例如:
{"id": 1, "name": "John"}
{"id": 2, "name": "Sarah"}

同时,jsonrepair 库还支持流支,可以处理无限大的文档。


目前 jsonrepair 在 Github 通过 MIT 协议开源,短短时间内有超过 1.3k 的 star、8.3k 的项目依赖量,是一个值得关注的前端开源项目。

2. 如何使用 jsonrepair

2.1 在 JavaScript 中使用 jsonrepair

首先需要安装相应的依赖:

npm install jsonrepair

下面是使用 ESM 模式导入并使用:

import {jsonrepair} from 'jsonrepair'
try {
// 以下是无效的 JSON,其中键缺少双引号,而字符串使用单引号:
  const json = "{name:'John'}"
  const repaired = jsonrepair(json)
  console.log(repaired)
  // 输出 '{"name":"John"}'
} catch (err) {
  console.error(err)
}

如果是 CommonJS 可以直接 require 相应模块即可:

const {jsonrepair} = require('jsonrepair')
const json = "{name:'John'}"
console.log(jsonrepair(json))
// 输出值 '{"name":"John"}'

开发者还可以直接使用 UMD 模式在浏览器中直接导入:

<script src="/node_modules/jsonrepair/lib/umd/jsonrepair.js"></script>
<script>
  const {jsonrepair} = JSONRepair
  const json = "{name:'John'}"
  console.log(jsonrepair(json)) // '{"name":"John"}'
</script>

同时,jsonrepair 还支持强大的流式操作,例如:

import {createReadStream, createWriteStream} from 'node:fs'
import {pipeline} from 'node:stream'
// 管道操作
import {jsonrepairTransform} from 'jsonrepair/stream'
// 转换流
const inputStream = createReadStream('./data/broken.json')
const outputStream = createWriteStream('./data/repaired.json')
pipeline(inputStream, jsonrepairTransform(), outputStream, (err) => {
  if (err) {
    console.error(err)
  } else {
    console.log('done')
  }
})
// 开发者还可以使用 .pipe() 替换 pipeline(),例如:
// inputStream
//   .pipe(jsonrepairTransform())
//   .pipe(outputStream)
//   .on('error', (err) => console.error(err))
//   .on('finish', () => console.log('done'))

2.2 在 Python 中使用 jsonrepair

开发者还可以通过 PythonMonkey 在 Python 中使用。

  • 第一步:通过 npm install jsonrepair 安装 jsonrepair
  • 第二步:通过 pip install pythonmonkey 安装 PythonMonkey
  • 第三步:在 Python 脚本中使用 jsonrepair
import pythonmonkey

jsonrepair = pythonmonkey.require('jsonrepair').jsonrepair

json = "[1,2,3,"
repaired = jsonrepair(json)
print(repaired)
// 输出 [1,2,3]

2.3 在 CLI 中使用 jsonrepair

使用 npm 全局安装 jsonrepair 后,开发者即可在命令行中使用。全局安装 jsonrepair 的步骤如下:

npm install -g jsonrepair
// 安装
jsonrepair [filename] {OPTIONS}
// 执行修复

下面是一些在 CLI 中使用 jsonrepair 的示例:

$ jsonrepair broken.json                        # Repair a file, output to console
$ jsonrepair broken.json > repaired.json        # Repair a file, output to file
$ jsonrepair broken.json --output repaired.json # Repair a file, output to file
$ jsonrepair broken.json --overwrite            # Repair a file, replace the file itself
$ cat broken.json | jsonrepair                  # Repair data from an input stream
$ cat broken.json | jsonrepair > repaired.json  # Repair data from an input stream, output to file

参考资料

https://github.com/josdejong/jsonrepair

https://github.com/RyanMarcus/dirty-json

https://josdejong.github.io/jsonrepair/

https://github.com/HAibiiin/json-repair

最近发表
标签列表