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)
标签:stringify,obj,name,JavaScript,score,console,null From: https://www.cnblogs.com/dissipate/p/16659809.html