JSON.stringify 安全模式
function JsonStringify ( source, replacer, space ) {
let stack = [ ] , selectKeys = Array. isArray ( replacer) && replacer. map ( v => typeof v == 'number' ? v. toString ( ) : v)
return JSON . stringify ( source, function ( key, value ) {
let isChild = stack. length > 0 , isCycle = false
if ( isChild) {
if ( selectKeys && ! selectKeys. includes ( key) ) return
let thisPos = stack. indexOf ( this )
thisPos != - 1 ? stack. splice ( thisPos + 1 ) : stack. push ( this )
isCycle = stack. includes ( value)
}
if ( typeof replacer == 'function' ) {
value = replacer . call ( this , key, value, isCycle)
if ( isChild) isCycle = stack. includes ( value)
}
if ( isCycle) return
if ( typeof value == 'bigint' ) value = value. toString ( )
if ( ! isChild) stack. push ( value)
return value
} , space)
}
使用示例
var w = { w1 : 1 , w2 : 2 }
var a = { a : 11 , b : 22 , c : [ 33 , w, 44 ] }
w. w3 = a
a. d = a
a. e = w
a. c[ 3 ] = a
JsonStringify ( a, null , 2 )
JsonStringify ( a, ( key, value, isCycle ) => isCycle ? '<circular>' : value, 2 )