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)
分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2020-09-05 字典扁平化
2020-09-05 functools
2020-09-05 python装饰器不改变原函数属性,带参装饰器