JSON 中序列化和反序列化 Function

序列化 Function

  • 通过 Function.prototype.toString 方法将函数转换成字符串
  • 自定义对象的 .JSON 方法
    • JSON.stringify 如果对象 obj 有一个名为 toJSON 的方法,JSON.stringify 会调用这个方法来获取序列化结果
    • 如果对象没有 toJSON 方法,JSON.stringify 会使用对象的原始属性进行序列化
// 示例对象
const obj = {
  name: 'example',
  func: function() {
    return 'a';
  }
};

// 自定义的 toJSON 方法来处理函数
obj.toJSON = function() {
  return {
    name: this.name,
    func: this.func.toString()  // 将函数转化为字符串
  };
};

// 序列化对象
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// 输出: {"name":"example","func":"function() { return 'a'; }"}

反序列化 Function

  • 通过 new Function 将字符串函数变成可执行的函数
// 反序列化 JSON
const jsonString = '{"name":"example","func":"function() { return \'a\'; }"}';
const jsonObject = JSON.parse(jsonString);

// 恢复函数
jsonObject.func = new Function('return ' + jsonObject.func)();

console.log(jsonObject.func()); // 输出: 'a'

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值