const stringify = (obj) => {
try {
return JSON.stringify(obj, (key, value) => {
if(typeof value === 'function') {
return `FUNCTION_FLAG ${value}`
} else {
return value
}
})
} catch (error) {
console.log(error)
return '出错了'
}
}
const parse = (jsonStr) => {
try {
return JSON.parse(jsonStr, (key, value) => {
if(value && typeof value === 'string') {
return value.indexOf('FUNCTION_FLAG') > -1 ? new Function(`return ${value.replace('FUNCTION_FLAG', '')}`)() : value
}
return value
})
} catch (error) {
console.log(error)
return '出错了'
}
}
const obj = {
name: '测试',
num: 10,
fn: (v) => {
return v
}
}
let str = stringify(obj)
let result = parse(str)
console.log(str) // {"name":"测试","num":10,"fn":"FUNCTION_FLAG function fn(v) {\n return v;\n }"}
console.log(result)
来源:https://www.cnblogs.com/yalong/p/15768087.html