重新解析网页中不正确编码的 JSON

前言

在调试网页或接口时,我们偶尔会遇到 JSON 内容整体乱码的情况
不论是中文,英文或其他语言,都有可能遇到 JSON 文件出现 测试、䏿–‡ 或 ���� 的乱码,这通常不是 JSON 本身损坏,而是响应数据的真实编码与浏览器解析时使用的编码不一致,例如服务端实际返回 UTF-8,却被按 GBK 解码,或者反过来

重新编码

按下 CTRL + SHIFT + J,CTRL + SHIFT + I 或 F12 以打开 DevTools
切换到“控制台”选项卡,将以下代码粘贴,即可重新编码 JSON

根据你需要的编码,修改 const ENCODING = 'utf-8'; 中 utf-8 部分
支持的编码:gbk、big5、shift-jis 等

重新编码并下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 指定编码
const ENCODING = 'utf-8';

fetch(location.href)
// 获取原始二进制数据
.then(res => res.arrayBuffer())
.then(buf => {
// 用指定的编码将字节转为字符串
const text = new TextDecoder(ENCODING).decode(buf);

try {
// 尝试解析为 JSON
const obj = JSON.parse(text);
const jsonStr = JSON.stringify(obj, null, 2);

// 自动下载文件
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `decoded_${Date.now()}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);

console.log('已成功解码,文件将开始下载。');
} catch (e) {
// 如果不是 JSON,另存为文本文件
console.warn('当前数据不为 JSON,将以文本文件保存。');
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `decoded_text_${Date.now()}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
})
.catch(err => console.error('请求失败,请检查网络或刷新以重试: ', err));

重新编码并替换当前页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 指定编码
const ENCODING = 'utf-8';

fetch(location.href)
// 获取原始二进制数据
.then(res => res.arrayBuffer())
.then(buf => {
// 用指定的编码将字节转为字符串
const text = new TextDecoder(ENCODING).decode(buf);

try {
// 尝试解析为 JSON
const obj = JSON.parse(text);
const jsonStr = JSON.stringify(obj, null, 2);

// 直接在页面显示(替换当前页面内容)
document.documentElement.innerHTML = `
<head><meta charset="utf-8"><title>decoded</title></head>
<body style="margin:0;padding:16px;background:#1e1e1e;color:#ddd;
font-family:Consolas,Monaco,monospace;white-space:pre-wrap;
word-break:break-all;">${jsonStr
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')}</body>
`;

console.log('已成功解码,内容已在页面显示。');
} catch (e) {
// 如果不是 JSON,直接在页面显示文本
console.warn('当前数据不为 JSON,将以文本形式在页面显示。');
document.documentElement.innerHTML = `
<head><meta charset="utf-8"><title>decoded</title></head>
<body style="margin:0;padding:16px;background:#1e1e1e;color:#ddd;
font-family:Consolas,Monaco,monospace;white-space:pre-wrap;
word-break:break-all;">${text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')}</body>
`;
}
})
.catch(err => console.error('请求失败,请检查网络或刷新以重试: ', err));