1、是什么
JSON.stringify 小程序开发定制方法将某个对象转换成 JSON 形式
const userInfo= { name: 'zs', age: 20}console.log(JSON.stringify(userInfo));// {"name":"zs","age":20}
- 1
- 2
- 3
- 4
- 5
- 6
2、语法
语法: 小程序开发定制可以有三个参数,小程序开发定制第一个是传入要的值,小程序开发定制第二个为函数或者数组,小程序开发定制第三个是文本添加缩进、空格和换行符
JSON.stringify(value[, replacer[, space]])
- 1
- value:第一个参数,将要序列后成 JSON 字符串的值。
- replacer:【可选】第二个参数
(1) 如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;
(2) 如果参数是一个数组,则仅转换该数组中具有键值的成员。成员的转换顺序与键在数组中的顺序一样。
(3) 如果该参数为未提供或者null ,则对象所有的属性都会被序列化。 - space:【可选】第三个参数,美化文本格式,文本添加缩进、空格和换行符,
(1) 如果 该参数 是一个数字,则返回值文本在每个级别缩进指定数目的空格
(2) 该参数最大值为10,如果 该参数大于 10,则文本缩进 10 个空格。
(3)该参数也可以使用非数字,如:\t。最大值为10
3、replacer用法
参数replacer: 为函数的时候
第一种情况为函数的时候,则它有两个参数,键(key) 和 值(value),并且两个参数都会被序列化。我们可以通过此函数过滤一些我们要操作的键值
- 序列化传入为对象时,若 replacer 函数返回 undefined 或者函数,则值会被忽略
- 1
// repalcer 接受两个参数 key valuefunction replacer(key, value) {// key value 分别为对象的每个键值对 if (typeof value === "string") { return undefined ; } return value;}const userInfo= { name: 'zs', age: 20, sex: '男'}console.log(JSON.stringify(userInfo, replacer));// {"age":20}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 序列化传的是数组,若 replacer 函数返回 undefined ,当前值不会被忽略,而将会被 null 取代。
- 1
function replacer(key, value) {// key value 分别为对象的每个键值对 if (typeof value === "string") { return undefined ; } return value;}const foodList= ['苹果',1,'2',222]console.log(JSON.stringify(foodList, replacer));// [null,1,null,222]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
参数replacer:为数组时
则仅转换该数组中具有键值的成员
const userInfo= { name: 'zs', age: 20, sex: '男'}console.log(JSON.stringify(userInfo, ['name','sex']));//{"name":"zs","sex":"男"}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4、注意点
- 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值
JSON.stringify([new Number(1), new String("String"), new Boolean(true)]);// [1,"String",true]
- 1
- 2
- 3
- 转换的值如果存在toJSON(),则toJSON() 方法返回什么值,序列化结果就返回什么值,其余值会被自动忽略
const userInfo= { name: 'zs', age: 20, sex: '男', toJSON(){ return '我是toJSON方法的返回值' }}console.log(JSON.stringify(userInfo));// "我是toJSON方法的返回值"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 出现Date 对象,则JSON.stringify() 会把Date 的值序列化 为时间格式字符串。
console.log(JSON.stringify(new Date()));// '"2022-03-11T06:51:12.812Z"'
- 1
- 2
- JSON.stringify()只能序列化可枚举属性,不可枚举的属性默认会被自动忽略
const userInfo= {}Object.defineProperty(userInfo, "work", { content: '遛狗', adrress: '广州', enumerable: false});Object.defineProperty(userInfo, "time", { value: '11.am', enumerable: true});console.log(JSON.stringify(userInfo));// {"time":"11.am"}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 出现Symbol值,则会被自动忽略
const userInfo= { name: 'zs', [Symbol('ageSymbol')]: 'ageSymbol'}console.log(JSON.stringify(userInfo));// {"name":"zs"}
- 1
- 2
- 3
- 4
- 5
- 6
…