前端技术之:JSON.stringfy详细说明

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


value 被序列化为字符串的对象

replacer 根据类型不同,其行为也不一样。如果是一个函数类型,则相当于是一个filter,可以对序列化的键值对进行加工处理;如果是一个数组,则只有符合数组中名称的key才会被输出

space 如果为0或不填,则不进行格式化处理;如果为大于0的数值,则表示每级缩进空格数;如果是一个字符串,则表示每级缩进时替代空格进行填充的字符串内容。


通过以下的data作为示例:

let data = { name: ‘wang‘, age: 28, address: null, favorites: undefined, company: { name: ‘world village‘, address: ‘Beijing city‘ }}

不加任何参数,直接输出:

console.log(JSON.stringify(data))

结果为:

{"name":"wang","age":28,"address":null,"company":{"name":"world village","address":"Beijing city"}}

第二个参数为数组:

console.log(JSON.stringify(data, [‘name‘, ‘age‘]))

结果为:

{"name":"wang","age":28}

第二个参数是一个函数:

console.log( JSON.stringify(data, (k, v) => { if (‘age‘ == k) { return undefined } return v }))

结果为:

{"name":"wang","address":null,"company":{"name":"world village","address":"Beijing city"}}

如果第三个参数为0或者null:

console.log(JSON.stringify(data, null, 0))

则结果为:

{"name":"wang","age":28,"address":null,"company":{"name":"world village","address":"Beijing city"}}

如果第三个参数为大于0的数值:

console.log(JSON.stringify(data, null, 2))

则结果为:

{ "name": "wang", "age": 28, "address": null, "company": { "name": "world village", "address": "Beijing city" }}

如果第三个参数为字符串:

console.log(JSON.stringify(data, null, ‘**‘))

则结果为:

{**"name": "wang",**"age": 28,**"address": null,**"company": {****"name": "world village",****"address": "Beijing city"**}}

如果过滤值为null或者undefined的键值对?

let data = { name: ‘wang‘, age: 28, address: null, favorites: undefined, men: true, women: false, company: { name: ‘world village‘, address: ‘Beijing city‘ }}console.log( JSON.stringify(data, (k, v) => { if (null != v && undefined != v) return v }))

相关文章