welcome

js如何在json中存储函数

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

posted @ 2023-03-21 15:27  一首弦曲献仙音  阅读(130)  评论(0编辑  收藏  举报
//博文图片放大缩小 //飘桃花效果