JSON.stringify() 的特性

const user= {
    "name" : "leo",
    "age" : 30
}

console.log(user)

//结果 [object Object]

console.log(JSON.stringify(user))

//结果 "{"name":"Leo","age": 30}"

第二个参数 (数组)

想查找某一键值时使用

console.log(JSON.stringify(user,['name']))

//结果 {"name" : "Leo"}

第二个参数 (函数)

返回需要的数据

JSON.stringify(user,(key,value) =>{
    if(typeof value === 'string') {
        return undefined;
    }
    return value;
});

//结果 {age : 30}

第三个参数为数字或者字符串

JSON.stringify({"name":"Leo","age":30},null,2)
//结果
//"{
//  "name": "Leo",
//  "age": 30
//}"

JSON.stringify({"name":"Leo","age":30},null,'**')
//"{
//**"name": "Leo",
//**"age": 30
//}"

JSON.stringify({"name":"Leo","age":30})
//"{"name":"Leo","age":30}"

toJSON方法

const user = {
    firstName : 'leo',    
    lastName : 'king',
    toJSON(){
        return {
            fullName:`${this.firstName}+${this.lastName}`
        }
    }
}

console.log(JSON.stringify(user)

//"{"fullName":'Leo King'}"
原文地址:https://www.cnblogs.com/wyLeoKing/p/12965437.html