JSON.stringfy() 的特性

130 阅读1分钟

在核心文件中查看 JSON 中包含的方法,有 parse 以及 stringfy

image.png

JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串。使用 JSON.stringfy() 的场景有很多,比如数据的深拷贝、接口传参前数据的转化。(深拷贝的坑:存在循环引用时会抛出错误)

对于 JSON.stringfy() 的研究,源于一次导入导出 JSON 功能的实现,要对最终的 JSON 数据的格式进行美化并显示,最终发现使用 JSON.stringfy() 的第三个参数即可实现

JSON.stringify(this.myJson,null,'\t')

下面来看一看具体的细节。

JSON.stringfy()

语法:

JSON.stringify(value[, replacer[, space]])

参数:

  • value:要转换的值(必填项)。

  • replacer:用于转换结果的函数或数组(非必填)

    • replacer 为函数,调用函数并传入每个成员的键和值。使用返回值而不是原始值。如果函数返回 undefined,则排除成员
    • replacer 为数组,仅转换该数组中具有键值的成员
  • space: 文本添加缩进、空格和换行符(非必填)

    • 如果 space 是一个数字,每个级别缩进指定数目的空格
    • 如果 space > 10,文本依旧缩进 10 个空格
    • space 也可以使用 \t 这种非数字形式

JSON.stringfy() 的特点:

  • 布尔值、数字、字符串类型的数据,JSON.stringfy() 后会自动转换成对应的原始值,日期类型会被转化为字符串
console.log(JSON.stringify([new Number(100)]))
console.log(JSON.stringify([new String("hello")]))
console.log(JSON.stringify([new Boolean(true)]))
console.log(JSON.stringify(new Date()));

image.png

  • JSON.stringfy() 会自动忽略不可枚举的属性(undefined、 symbol 、函数)
console.log(function test() { return true});
console.log(undefined);
console.log(Symbol(1));
console.log(JSON.stringify([undefined, function test() { return true }, Symbol(1)]) )

image.png

其它

JSON 数据太多时,可以使用在线 JSON 工具进行格式化以及格式校验,方便排查问题。

6d2087b6c319f3940b2ad33eaf2c176.png

f6e8c2326e09abe5c40c4268c988390.png