蓝色天空网mbsky.com · 知识 · 实践 · 创造JSON · 本地阅读预览
教程 / 前端开发 / JSON

JSON.stringify 的筛选、排版与类型边界

理解对象、数组、日期与函数字符串的序列化,正确处理replacer、space和异常。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

三个参数与返回结果

text · 阅读源码
JSON.stringify(value, replacer, space)
参数或结果含义条件与边界
value待转换的JavaScript值可能先调用对象的toJSON;不保证任意值都能转换
replacer函数接收key与value,返回替换值普通函数的this是当前持有成员的对象;根以空字符串key调用
replacer数组字符串、数字及其String/Number包装对象组成的属性名单转换为字符串属性名并去重;其他类型忽略;对子对象也生效,不筛选数组索引
space数字每级缩进的空格数先截断为整数,再限为最多10;小于1时不缩进;也支持Number包装对象
space字符串每级缩进文本仅取最前10个UTF-16码元;任意字符不一定形成合法JSON空白
返回值序列化字符串,或undefined不能用返回undefined等同输出文本null
异常TypeError等循环引用、默认BigInt行为会抛错;用户toJSON/replacer也可能抛错

JSON.stringify输出的是字符串,方便存文件或发送HTTP消息;它不把对象原地改成字符串。replacer和space都可省略,第二参数写null表示不筛选。

把对象序列化为文本

javascript · 阅读源码
"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 site = {name: "蓝色天空网", url: "https://mbsky.com", enabled: true};
const text = JSON.stringify(site);
show("文本", text);
show("类型", typeof text);
show("原值仍为对象", typeof site);
show("再解析的名称", JSON.parse(text).name);
蓝色天空网站点对象

所需环境:现代浏览器

当前源码 SHA256:7650e9b2b74a33c5a6089af0d63a2298c58dce3aa03c5927317654b337246d9d

下载本站示例源码
预期结果 · 待实际运行核验
  • 文本: {"name":"蓝色天空网","url":"https://mbsky.com","enabled":true}
  • 类型: string
  • 原值仍为对象: object
  • 再解析的名称: 蓝色天空网

通常处理可枚举的自有字符串键属性;Symbol键不进入JSON。对象上的函数、undefined和Symbol值通常会被忽略。JSON文本中的名称始终带双引号。

把数组序列化为文本

javascript · 阅读源码
"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 courses = ["HTML5", "CSS", "JavaScript"];
show("课程", JSON.stringify(courses));
show("不可直接表示的数组值", JSON.stringify([undefined, function () {}, Symbol("x")]));
const sparse = ["HTML5", "CSS", "JavaScript"];
delete sparse[1];
show("空槽与长度", sparse.length);
show("空槽序列化", JSON.stringify(sparse));
教程数组与特殊元素

所需环境:现代浏览器

当前源码 SHA256:5b91354f673cec008e854740f1af89ee19f325d2c58879902d396b0797100598

下载本站示例源码
预期结果 · 待实际运行核验
  • 课程: ["HTML5","CSS","JavaScript"]
  • 不可直接表示的数组值: [null,null,null]
  • 空槽与长度: 3
  • 空槽序列化: ["HTML5",null,"JavaScript"]

数组按0到length-1读取索引位置;额外字符串属性不会因此进入JSON。数组空槽或无法表示的元素用null占位,区别于对象成员被省略。

函数筛选、属性名单和缩进

javascript · 阅读源码
"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 = {name: "蓝色天空网", token: "demo-only", nested: {name: "教程", token: "nested-demo"}};
const text = JSON.stringify(data, function (key, value) {
  if (key === "token") return undefined;
  return value;
}, 2);
show("筛选结果", text);
show("根值也可被替换", JSON.stringify({name: "蓝色天空网"}, function (key, value) {
  return key === "" ? "替换整个根" : value;
}));
按规则去除内部字段

所需环境:现代浏览器

当前源码 SHA256:899eb9c5a2a60bb252ff8dcf78bb0029dc25001bc1c7fccf897efed377e356eb

下载本站示例源码
预期结果 · 待实际运行核验
  • 两级token都不出现在输出中
  • 输出name与nested,缩进为2空格
  • 根值也可被替换: "替换整个根"
javascript · 阅读源码
"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 sites = [{name: "蓝色天空网", url: "https://mbsky.com", internal: true}];
show("名单", JSON.stringify(sites, ["name"]));
show("保留两项", JSON.stringify(sites, ["name", "url"]));
show("紧凑", JSON.stringify({name: "蓝色天空网", enabled: true}));
show("两空格", JSON.stringify({name: "蓝色天空网", enabled: true}, null, 2));
名单对嵌套对象也生效

所需环境:现代浏览器

当前源码 SHA256:3f8c462be614a263927270e8b312719a2f4ab3ea1380b1952bb720bfd48f51b0

下载本站示例源码
预期结果 · 待实际运行核验
  • 名单: [{"name":"蓝色天空网"}]
  • 保留两项: [{"name":"蓝色天空网","url":"https://mbsky.com"}]
  • 紧凑与两空格版本表达相同数据

名单不是数组索引选择器:["name"]没有删除数组第0项,而是筛选该项对象的属性。若根对象里还有sites成员,名单也要包含sites,才能继续进入这个成员。

序列化筛选不是服务端授权控制。对外输出应先建立明确的数据传输对象,并测试每个嵌套层。space建议只使用JSON允许的空白;非空白字符在实际插入缩进的非空对象或数组中通常会产生非法JSON。顶层原始值、空对象和空数组未插入缩进时,不能据此断言结果一定非法。

javascript · 阅读源码
"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 = {name: "蓝色天空网", hidden: true};
show("包装属性名单", JSON.stringify(data, [new String("name"), new Number(7), "name", true]));
show("小数缩进", JSON.stringify(JSON.stringify({a: 1}, null, 3.8)));
show("缩进上限", JSON.stringify(JSON.stringify({a: 1}, null, 12)));
show("包装制表符", JSON.stringify(JSON.stringify({a: 1}, null, new String("\t"))));
const invalid = JSON.stringify({a: 1}, null, "x");
try { JSON.parse(invalid); } catch (error) { show("非空对象缩进", error.name); }
show("原始值仍可解析", JSON.parse(JSON.stringify(5, null, "x")));
show("空对象仍可解析", JSON.parse(JSON.stringify({}, null, "x")));
缩进上限、非法空白与包装属性名

所需环境:现代浏览器

当前源码 SHA256:d3b2b3f0e1069568a497286eb524164e5238020dc7d0066a2b0c42a1c30cd03e

下载本站示例源码
预期结果 · 待实际运行核验
  • 包装属性名单仅包含name,值为蓝色天空网;数字7没有对应成员,布尔true被忽略
  • 小数3.8缩进为3空格;12缩进限制为10空格;String包装的制表符可用
  • 非空对象使用x缩进后JSON.parse抛SyntaxError
  • 原始值仍可解析: 5
  • 空对象仍可解析: {}

Date与toJSON

javascript · 阅读源码
"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 = {name: "蓝色天空网", publishedAt: new Date("2024-01-02T03:04:05Z")};
const text = JSON.stringify(data);
show("文本", text);
show("解析后类型", typeof JSON.parse(text).publishedAt);
show("无效日期", JSON.stringify({date: new Date("not-a-date")}));
明确UTC日期及无效日期

所需环境:现代浏览器

当前源码 SHA256:8b1440525ea7935fc42120ddbbed2633a2e90a39c567e2f4dcf2c1e96b19052c

下载本站示例源码
预期结果 · 待实际运行核验
  • 文本含"publishedAt":"2024-01-02T03:04:05.000Z"
  • 解析后类型: string
  • 无效日期: {"date":null}

Date的toJSON通常调用toISOString输出UTC字符串;无效Date在此转换中得到null。JSON.parse不会自动把字符串还原为Date,必须按协议显式恢复。自定义toJSON可以改变对象序列化结果,需审查是否遗漏业务字段。

函数被省略与保留函数文本的差异

javascript · 阅读源码
"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 = {name: "蓝色天空网", score: function () { return 100; }, missing: undefined};
show("对象", JSON.stringify(data));
show("顶层函数", JSON.stringify(function () {}));
show("顶层undefined", JSON.stringify(undefined));
对象函数不进入JSON

所需环境:现代浏览器

当前源码 SHA256:f83c095ed1d2c832e78a5eaa0906696cf6cc68dbec131ce4c4d8f3626567f849

下载本站示例源码
预期结果 · 待实际运行核验
  • 对象: {"name":"蓝色天空网"}
  • 顶层函数: undefined
  • 顶层undefined: undefined
javascript · 阅读源码
"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 = {name: "蓝色天空网", explanation: function () { return "理解以后再动手"; }};
data.explanation = data.explanation.toString();
const text = JSON.stringify(data);
const restored = JSON.parse(text);
show("文本", text);
show("还原后字段类型", typeof restored.explanation);
show("本站固定文案", "理解以后再动手");
toString只保留普通文字

所需环境:现代浏览器

当前源码 SHA256:1c3956cd398475d6b021d91147ce520e4e7628fadcc06a907fa98a0b661502e0

下载本站示例源码
预期结果 · 待实际运行核验
  • 文本包含函数源码的转义字符串
  • 还原后字段类型: string
  • 本站固定文案: 理解以后再动手

toString不是函数序列化协议:闭包变量、原生实现、绑定状态和外部依赖不会可靠恢复。保留历史上把函数转字符串的知识,但不要接着eval。跨系统应交换数据或受控操作名称。

特殊值、循环与精度

javascript · 阅读源码
"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";
}
show("非有限数", JSON.stringify({a: NaN, b: Infinity, c: -Infinity}));
for (const [name, value] of [["BigInt", 123n], ["循环对象", (() => {const x = {}; x.self = x; return x;})()]]) {
  try { JSON.stringify(value); }
  catch (error) { show(name, error.name); }
}
show("精确标识用字符串", JSON.stringify({id: "9007199254740993"}));
对异常和特殊值做显式分支

所需环境:现代浏览器

当前源码 SHA256:8bd947f46b66267f8426885278cbdf01041017899f6a353b828300f01f24dfe3

下载本站示例源码
预期结果 · 待实际运行核验
  • 非有限数: {"a":null,"b":null,"c":null}
  • BigInt: TypeError
  • 循环对象: TypeError
  • 精确标识用字符串: {"id":"9007199254740993"}

默认情况下BigInt不直接转换为JSON数字,循环引用也不能直接输出。可以按接口约定把BigInt转成十进制字符串;这属于数据契约,接收端需明确还原。JSON.parse(JSON.stringify(x))会丢失多种类型与引用关系,不能当作通用深拷贝。

基础支持和新特性分开核对

浏览器基础版本说明
Chrome3基础parse/stringify
Edge12不能与IE混为一列
Firefox3.5基础parse/stringify
Internet Explorer8只保留历史背景
Safari4基础parse/stringify
Opera10.5不把10写成精确最低版本

这张表仅描述基础JSON.stringify的历史支持。不要把旧式浏览器列表与现代BigInt语法、Object.hasOwn或新JSON扩展的支持混为一谈,实例应在目标环境实际验证。

常见错误与边界

  • 对象省略与数组null占位混淆
  • 白名单忘记外层成员
  • 认为Date会自动还原
  • 序列化替代授权
  • 把undefined当JSON文本

练习与解答

JSON.stringify([{name:'蓝色天空网',url:'https://mbsky.com'}],['name'])输出什么,为什么不是空数组?

展开参考解答

输出[{"name":"蓝色天空网"}];名单筛选数组元素内的对象属性,并不选择数组索引。

规范与官方依据