JSON.parse 的参数、复原与网络数据
掌握返回类型、reviver、日期、网络错误、大整数与历史函数恢复的区别。
学完这一章,你能够
- 解析六类值
- 准确使用reviver
- 区分请求、解析和业务错误
参数、返回值与异常
| 项 | 类型或规则 | 返回/异常与环境 |
|---|---|---|
| text | 将输入转为字符串后按JSON语法解析 | 返回对象、数组、字符串、数字、布尔或null;不总是对象 |
| reviver | 可选函数,按由内向外的过程转换值 | 非可调用值被忽略;返回undefined会删除属性,最后处理根值的空键 |
| 异常 | 无效JSON抛SyntaxError | reviver自身抛出的异常也会向外传播 |
| 环境 | 浏览器或提供JSON API的JS运行时 | 网络请求并非JSON.parse的功能 |
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const data = JSON.parse('{"name":"蓝色天空网","rank":100,"site":"https://mbsky.com"}');
show("名称", data.name);
show("站点", data.site);
show("顶层数字", JSON.parse("42"));
try { JSON.parse('{"name":}'); } catch (error) { show("错误类型", error.name); }所需环境:现代浏览器
当前源码 SHA256:776b2eb5842f653e982ee899b3974cf3f1e3387326f0d9d420f9cdfa36744c96
- 名称: 蓝色天空网
- 站点: https://mbsky.com
- 顶层数字: 42
- 错误类型: SyntaxError
解析器接受数据不代表字段已验证。先解析,再检查结果是否为预期对象、字段是否存在、类型和范围是否正确。空HTTP响应不是null文本,交给JSON.parse会失败。
保留对象与数组两种网络输入
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
fetch("./site.json")
.then(response => {
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
})
.then(data => {
if (typeof data.name !== "string") throw new TypeError("缺少字符串name");
show("服务端名称", data.name);
})
.catch(error => show("请求或数据错误", error.message));所需环境:本地HTTP服务;项目site.json与index.html同目录
当前源码 SHA256:3a807c956c67dd0601d7026075aca087dd3b171ca4f6d5fd5b76522befe9ef39
- HTTP成功并取得site.json时输出服务端名称: 蓝色天空网
- 404进入错误分支,不能冒充JSON语法错误
- JSON错误或缺少name时给出数据错误
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
if (xhr.status < 200 || xhr.status >= 300) {
show("HTTP错误", xhr.status);
return;
}
try {
const data = JSON.parse(xhr.responseText);
if (!data || typeof data.name !== "string" || !Array.isArray(data.sites)) throw new TypeError("期待含字符串name与sites数组的对象");
show("服务端名称", data.name);
show("站点数", data.sites.length);
} catch (error) { show("数据错误", error.message); }
};
xhr.onerror = () => show("网络错误", "请求未完成");
xhr.open("GET", "./site.json", true);
xhr.send();所需环境:本地HTTP服务;完整对象数据site.json存在
当前源码 SHA256:1e0a7057ea607da67b1becea95307ab102b6bf5c403bc54a337cc48b1325fb0f
- 正常HTTP完成时输出服务端名称: 蓝色天空网
- 站点数: 3
- readyState未到4不读取;HTTP、解析和网络失败有分支
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const xhr = new XMLHttpRequest();
xhr.open("GET", "./sites.json");
xhr.responseType = "text";
xhr.onload = () => {
try {
if (xhr.status < 200 || xhr.status >= 300) throw new Error("HTTP " + xhr.status);
const values = JSON.parse(xhr.responseText);
if (!Array.isArray(values) || typeof values[1] !== "string") throw new TypeError("期待至少两项字符串数组");
show("第二项", values[1]);
} catch (error) { show("数据错误", error.message); }
};
xhr.onerror = () => show("网络错误", "请求未完成");
xhr.send();所需环境:本地HTTP服务;sites.json存在
当前源码 SHA256:a01d10da2f46d39e0cd6a540ec0ca067fc38b1aaa2fe8578c461acbc714bbecd
- HTTP成功时输出第二项: 学习
- 网络错误、HTTP失败、JSON解析失败和业务形状错误有分支
保留XMLHttpRequest作为既有接口知识,现代项目也可用fetch。response.json()已完成解析,不应再把得到的对象交给JSON.parse。服务端文本文件使用什么扩展名不决定数据语法;响应内容及媒体类型需要一致。
日期先以字符串交换,再按契约转换
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const data = JSON.parse('{"name":"蓝色天空网","createdAt":"2024-01-02T03:04:05.000Z"}');
show("原字段类型", typeof data.createdAt);
const date = new Date(data.createdAt);
if (Number.isNaN(date.getTime())) throw new RangeError("无效日期");
show("UTC时间", date.toISOString());所需环境:现代浏览器
当前源码 SHA256:46344d5daae2647d2083c75e852488c589d79ce1b5a676a117069f07bb431a37
- 原字段类型: string
- UTC时间: 2024-01-02T03:04:05.000Z
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const data = JSON.parse('{"name":"蓝色天空网","createdAt":"2024-01-02T03:04:05.000Z","rank":100}', function (key, value) {
if (key === "createdAt") {
const date = new Date(value);
if (Number.isNaN(date.getTime())) throw new RangeError("日期无效");
return date;
}
return value;
});
show("日期实例", data.createdAt instanceof Date);
show("UTC时间", data.createdAt.toISOString());
show("其他值", data.rank);所需环境:现代浏览器
当前源码 SHA256:2f02a66e7ada3ed1b93892695183842c60bb7ca19b3ce13bc980572383c2786a
- 日期实例: true
- UTC时间: 2024-01-02T03:04:05.000Z
- 其他值: 100
JSON没有Date类型;字符串不会自动变Date。日期格式与时区需在协议中约定,示例使用明确UTC的Z格式。任意字符串都转Date会误改普通文字;对无效输入也不能直接调用toISOString。
删除、根值和精度
const value = JSON.parse('{"keep":1,"remove":2}', function (key, value) {
if (key === "remove") return undefined;
return value;
});
// value只保留keep;数组位置返回undefined会形成空槽。
// 根值最后以key===""传入;忘记return value可能让整个结果变undefined。reviver按内层优先处理值,根值也会调用。返回undefined是删除行为,不是把JSON值改成null。若数值已经被Number舍入,普通reviver不能仅靠这个舍入后的value还原原数字。
较新的实现可向reviver传入context,对未修改的基本值提供source原始片段;须单独检测该能力,不能把基础JSON.parse的历史支持版本套到它上面。跨环境接口优先用字符串传递大整数。
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const order = [];
const result = JSON.parse('{"nested":{"keep":1,"drop":2},"items":[10,20]}', function (key, value) {
order.push(key);
if (key === "drop" || (Array.isArray(this) && key === "1")) return undefined;
return value;
});
show("嵌套对象", result.nested);
show("数组长度", result.items.length);
show("数组索引1存在", Object.hasOwn(result.items, "1"));
show("数组序列化", JSON.stringify(result.items));
show("先访问子项", order.indexOf("keep") < order.indexOf("nested"));
show("最后是根", order.at(-1) === "");
show("忘记返回值", JSON.parse('{"name":"蓝色天空网"}', function () {}));
show("只删除根", JSON.parse('42', (key, value) => key === "" ? undefined : value));所需环境:现代浏览器
当前源码 SHA256:64ad6cddd14440aa0fe0b377e6a825a2d078fcfc4e60c0cb82866128f2884c3e
- 嵌套对象: {"keep":1}
- 数组长度: 2
- 数组索引1存在: false
- 数组序列化: [10,null]
- 先访问子项: true
- 最后是根: true
- 忘记返回值: undefined
- 只删除根: undefined
"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const text = '{"id":9007199254740993}';
show("普通Number解析", JSON.parse(text).id);
let supported = false;
JSON.parse('0', (key, value, context) => {
supported = !!context && context.source === "0";
return value;
});
show("支持context.source", supported);
if (supported) {
const data = JSON.parse(text, (key, value, context) => key === "id" ? BigInt(context.source) : value);
show("精确标识", data.id.toString());
show("字段类型", typeof data.id);
} else {
show("迁移方案", JSON.parse('{"id":"9007199254740993"}').id);
}
// 普通reviver若只使用value,数值舍入已经发生;跨环境协议优先传字符串标识。所需环境:现代浏览器;context.source分支先做能力检测
当前源码 SHA256:7faf4028f9e98e4a5d9850e206a712099cc38c49a501b23269ed7e5ed987025f
- 普通Number解析: 9007199254740992
- 先观察支持context.source的布尔值;支持时精确标识为9007199254740993且字段类型bigint
- 不支持时输出字符串标识的迁移方案9007199254740993;不能伪称恢复了已经舍入的Number
函数字符串不是可移植数据
// 只读历史步骤,不执行:
// const data = JSON.parse(text);
// data.rank = eval("(" + data.rank + ")");
// const result = data.rank();
// 这会把文本当程序运行,不能当作JSON.parse本身支持函数。"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const data = JSON.parse('{"name":"蓝色天空网","operation":"rank","functionText":"function () { return 100; }"}');
const actions = {rank: () => 100};
show("函数文本类型", typeof data.functionText);
if (!Object.hasOwn(actions, data.operation)) throw new Error("未知操作");
show("本站允许的操作结果", actions[data.operation]());所需环境:现代浏览器
当前源码 SHA256:767c34e7e287942e8cf369ba933fff4c8e4bf18c8dccc70ef408f912730e750c
- 函数文本类型: string
- 本站允许的操作结果: 100
历史代码可能把函数存成字符串后再eval恢复。JSON.parse本身只会返回字符串,不会执行函数;动态执行数据文本还原函数会丢失闭包环境并引入代码执行风险。需要动作时传操作标识,由本站受控函数表处理,保留历史知识但不作为新写法推荐。
基础能力与后续特性分别核验
| 浏览器 | 基础最低版本记录 | 说明 |
|---|---|---|
| Chrome | 3 | 基础parse/stringify |
| Edge | 12 | 不能与IE混为一列 |
| Firefox | 3.5 | 基础parse/stringify |
| Internet Explorer | 8 | 只保留历史背景 |
| Safari | 4 | 基础parse/stringify |
| Opera | 10.5 | 不把10写成精确最低版本 |
兼容数据按JSON.parse这一具体特性查阅,不能混淆IE与Edge,也不能用基础API支持证明reviver context可用。旧浏览器曾通过JSON-js补充能力;新项目通常直接使用目标现代运行环境并测试实际特性。
常见错误与边界
- 忘记reviver返回原值
- 把Date字符串当Date实例
- 重复解析response.json结果
- 把空响应当null文本
- 函数字符串直接eval
练习与解答
reviver对remove返回undefined、对其他键也遗漏return时,会发生什么?
展开参考解答
remove被删除,其余值也可能被删除,最后根调用返回undefined可让整个parse结果变undefined;默认分支必须return value。