js 如何把 obj 转换成字符串 (包含函数)?

我有一个这样的字符串

const str = `{
  name:'v-custom',
  data(){
    return {
      hi:'666'
    }
  },
  mounted(){
    console.log('mounted',this)
  },
  methods:{
    showMsg(){
      console.log('this',this)
      // this.$Router.push('/v-edit')
    }
  }
}`
const formatObj = new Function(`return ${str}`)()
formatObj.el = 'chart681759405592'//新增一个 el 属性
console.log('formatObj',formatObj)

执行之后
image.png

现在我想把这个 obj 转换成字符串,请教大佬们 有没有方法?

阅读 1.9k
2 个回答

JSON.stringify默认会忽略function, undefined, 可使用第二个参数解决此问题

JSON.stringify(obj, function(key, value) {
  if(Object.prototype.toString.call(value) === '[object Function]') {
    return value.toString()
  }
  if(typeof value === 'undefined') {
    return ''
  }
  return value
})

测试一下

var a= {
    b: function() {
      alert('1')
    },
    bb: '123',
    c: {
      f: '1',
      nn: function() {}
    },
    hh: undefined
  }

  console.log(JSON.stringify(a, function(key, value) {
    if(Object.prototype.toString.call(value) === '[object Function]') {
      return value.toString()
    }
    if(typeof value === 'undefined') {
      return ''
    }
    return value
  }))

结果:

{"b":"function() {\n      alert('1')\n    }","bb":"123","c":{"f":"1","nn":"function() {}"},"hh":""}

至于其他判断逻辑可以根据自己的业务自行添加, 比如说a(){ return 111 }

  var a = {
    b: function () {
      alert('1')
    },
    bb: '123',
    c: {
      f: '1',
      nn: function () { }
    },
    hh: undefined,
    test() { alert('你知道就算大雨让这座城池颠倒') }
  }

  console.log(JSON.stringify(a, function (key, value) {
    if (Object.prototype.toString.call(value) === '[object Function]') {
      const str = value.toString()
      if (value.name && str.indexOf('function') === -1) {
        return str.replace(value.name, 'function')
      }
      return str
    }
    if (typeof value === 'undefined') {
      return ''
    }
    return value
  }, 2))

JSON.stringify()

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题