前端技术之JSONstringfy详细说明

8次阅读

共计 1506 个字符,预计需要花费 4 分钟才能阅读完成。

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
    })
)

正文完
 0