JavaScript: stringify

 

复制代码
const obj = {
    name: 'qwer',
    hobbies: ['op', 'nm'],
    year: 2022,
    fn: function () { },  // function ignore
    reg: new RegExp(),  // RegExp {}
    undefined: undefined,  // undefined ignore
    null: null,  // null
    nan: NaN,  // null
    infinity: Infinity,  // null
    'n-infinity': -Infinity,  // null
    date: new Date()  // 2022-09-05T13:24:48.358Z 
}

console.log(JSON.stringify(obj))
复制代码

 

复制代码
function Person(name) {
    this.name = name
}

Person.prototype.age = 55

p = new Person('qwer')
console.log(p);
console.log(JSON.stringify(p));  // 只处理对象自身属性
复制代码

 

第二参数:

const obj = {
    name: 'qwer',
    hobbies: ['op', 'nm'],
    year: 2022,
    date: new Date()  // 2022-09-05T13:24:48.358Z 
}

console.log(JSON.stringify(obj, ['name', 'date']));

只序列化name & date

 

replacer:

复制代码
const obj = [
    {
        name: 'aa',
        score: 100
    },
    {
        name: 'bb',
        score: 95
    },
    {
        'name': 'cc',
        score: 88
    },
    {
        'name': 'dd',
        score: 5
    }
]

function replacer(key, value) {
    if (key === 'score') {
        if (value >= 90) {
            return 'A'
        } else if (value >= 60) {
            return 'B'
        } else {
            return 'C'
        }
    }
    return value
}

console.log(JSON.stringify(obj, replacer));
复制代码

 

pretty

 

复制代码
const obj = [
    {
        name: 'aa',
        score: 100
    },
    {
        name: 'bb',
        score: 95
    },
    {
        'name': 'cc',
        score: 88
    },
    {
        'name': 'dd',
        score: 5
    }
]



console.log(JSON.stringify(obj, null, 2));
复制代码

 

 toJSON:

复制代码
const obj = {
    name: 'qwer',
    hobbies: ['op', 'nm'],
    year: 2022,
    toJSON:function(){
        return this.name+','+this.hobbies
    }
}

console.log(JSON.stringify(obj));
复制代码

 

循环引用

const c={
    name:'qw'
}

c.cc=c

JSON.stringify(c)

 

posted @   ascertain  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-09-05 字典扁平化
2020-09-05 functools
2020-09-05 python装饰器不改变原函数属性,带参装饰器
点击右上角即可分享
微信分享提示