https://mp.weixin.qq.com/s/5B_oxmnx9W9TLp9qBiv6sg
API
JSON 是一种基于文本的轻量级的数据交换格式。它可以被**任何的编程语言读**取和作为数据格式来传递。
JSON 可以表示数字、布尔值、字符串、null、数组(值的有序序列),以及由这些值(或数组、对象)所组成的对象(字符串与的映射)。
JSON 使用 JavaScript 语法,但是 JSON 格式仅仅是一个文本。文本可以被任何编程语言读取及作为数据格式传递。
JSON.stringfy
var a = { name: "lisi" };console.log(JSON.stringify(a))// {"name":"lisi"}console.log(JSON.stringify(a,null,4))//{// "name": "lisi"//}
- 注意可以使用第二个参数和第三个参数格式化输出结果
- 如果存在循环引用的现象,会报错。
- 慎用JSON.stringify
注意事项
转换属性值中有 toJSON 方法,慎用
转换值中如果有 toJSON 方法,该方法返回的值将会是最后的序列化结果
// toJSONlet toJsonMyIntro = {name: "Gopal",age: 25,like: "FE",toJSON: function () {return "前端杂货铺";},};console.log(JSON.stringify(toJsonMyIntro)); // "前端杂货铺"
被转换值中有 undefined、任意的函数以及 symbol 值,慎用
JSON.stringify([undefined, Object, Symbol("")]);// '[null,null,null]'JSON.stringify({ x: undefined, y: Object, z: Symbol("") });// '{}'
包含循环引用的对象,慎用
会报以下错误:
Uncaught TypeError: Converting circular structure to JSON--> starting at object with constructor 'Object'| property 'age' -> object with constructor 'Object'--- property 'name' closes the circleat JSON.stringify (<anonymous>)at <anonymous>:1:6
以 symbol 为属性键的属性,慎用
所有以 symbol 为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。
值为 NaN 和 Infinity,慎用
数组的值,或者非数组对象属性值为 NaN 和 Infinity 的,会被转换成 null
具有不可枚举的属性值时,慎用
不可枚举的属性默认会被忽略:
