0


JSON.stringify用法

1、是什么
JSON.stringify 方法将某个对象转换成 JSON 字符串形式

const userInfo={
    name:'zs',
    age:20}
console.log(JSON.stringify(userInfo));// {"name":"zs","age":20}

2、语法
语法: 可以有三个参数,第一个是传入要序列化的值,第二个为函数或者数组,第三个是文本添加缩进、空格和换行符

JSON.stringify(value[, replacer[, space]])
  • value:第一个参数,将要序列后成 JSON 字符串的值。
  • replacer:【可选】第二个参数 (1) 如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理; (2) 如果参数是一个数组,则仅转换该数组中具有键值的成员。成员的转换顺序与键在数组中的顺序一样。 (3) 如果该参数为未提供或者null ,则对象所有的属性都会被序列化。
  • space:【可选】第三个参数,美化文本格式,文本添加缩进、空格和换行符, (1) 如果 该参数 是一个数字,则返回值文本在每个级别缩进指定数目的空格 (2) 该参数最大值为10,如果 该参数大于 10,则文本缩进 10 个空格。 (3)该参数也可以使用非数字,如:\t。最大值为10

3、replacer用法

参数replacer: 为函数的时候

第一种情况为函数的时候,则它有两个参数,键(key) 和 值(value),并且两个参数都会被序列化。我们可以通过此函数过滤一些我们要操作的键值

 - 序列化传入为对象时,若 replacer 函数返回 undefined 或者函数,则值会被忽略
// repalcer 接受两个参数 key value
function replacer(key,value){// key value 分别为对象的每个键值对if(typeofvalue==="string"){return undefined ;}returnvalue;}const userInfo={
    name:'zs',
    age:20,
    sex:'男'}
console.log(JSON.stringify(userInfo, replacer));// {"age":20}
- 序列化传的是数组,若 replacer 函数返回 undefined ,当前值不会被忽略,而将会被 null 取代。
function replacer(key,value){// key value 分别为对象的每个键值对if(typeofvalue==="string"){return undefined ;}returnvalue;}const foodList=['苹果',1,'2',222]
console.log(JSON.stringify(foodList, replacer));// [null,1,null,222]

参数replacer:为数组时

则仅转换该数组中具有键值的成员

const userInfo={
    name:'zs',
    age:20,
    sex:'男'}
console.log(JSON.stringify(userInfo,['name','sex']));//{"name":"zs","sex":"男"}

4、注意点

  • 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值
JSON.stringify([newNumber(1),newString("String"),newBoolean(true)]);// [1,"String",true]
  • 转换的值如果存在toJSON(),则toJSON() 方法返回什么值,序列化结果就返回什么值,其余值会被自动忽略
const userInfo={
    name:'zs',
    age:20,
    sex:'男',toJSON(){return'我是toJSON方法的返回值'}}
console.log(JSON.stringify(userInfo));// "我是toJSON方法的返回值"
  • 出现Date 对象,则JSON.stringify() 会把Date 的值序列化 为时间格式字符串。
console.log(JSON.stringify(newDate()));// '"2022-03-11T06:51:12.812Z"'
  • 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"}
  • 出现Symbol值,则会被自动忽略
const userInfo={
  name:'zs',[Symbol('ageSymbol')]:'ageSymbol'}
console.log(JSON.stringify(userInfo));// {"name":"zs"}

标签: json javascript 前端

本文转载自: https://blog.csdn.net/Smile_666666/article/details/123421697
版权归原作者 Smile_zxx 所有, 如有侵权,请联系我们删除。

“JSON.stringify用法”的评论:

还没有评论