【转】带有function的JSON对象的序列化与还原

JSON对象的序列化与反序列化相信大家都很熟悉了。基本的api是JSON.parse与JSON.stringify.

复制代码
复制代码
复制代码
var json={
    uiModule:'http://www.a.com',
    login:'true',
    mainSubjectId:3004,
    happydays:100,
    happyhours:1,
    userCount :200,
    itemCount:1000000,
    type:'all',
    mainSubjectId:3004,
    taglist:[
        {'tagName':'xiaoc','applyItemCount':20},
        {'tagName':'xiaoc','applyItemCount':20}
    ]
}

var s=JSON.stringify(json)
复制代码
复制代码
复制代码

 

输出:

复制代码
"{"uiModule":"http://www.a.com","login":"true","mainSubjectId":3004,"happydays":100,"happyhours":1,"userCount":200,"itemCount":1000000,"type":"all","taglist":[{"tagName":"xiaoc","applyItemCount":20},{"tagName":"xiaoc","applyItemCount":20}]}"

JSON.parse(s)
复制代码

 

输出:

 ok 到现在为止都没啥问题,处理得很好,但是现在我有这么一个json对象

复制代码
复制代码
复制代码
var json={
  name:'json',
  getName:function(){
     return this.name;   
  }
}
复制代码
复制代码
复制代码

 

我们看下JSON.stringify(json)输出啥

"{"name":"json"}"

尼玛把getName弄丢了 ,怎么办呢?其实大家都没注意到JSON.stringify还有些参数

 

复制代码
复制代码
复制代码
JSON.stringify(value [, replacer] [, space])

value

Required. A JavaScript value, usually an object or array, to be converted.

replacer

Optional. A function or array that transforms the results.

If replacer is a function, JSON.stringify calls the function, passing in the key and value of each member. The return value is used instead of the original value. If the function returns undefined, the member is excluded. The key for the root object is an empty string: "".

If replacer is an array, only members with key values in the array will be converted. The order in which the members are converted is the same as the order of the keys in the array. The replacer array is ignored when thevalue argument is also an array.

space

Optional. Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

If space is omitted, the return-value text is generated without any extra white space.

If space is a number, the return-value text is indented with the specified number of white spaces at each level. Ifspace is greater than 10, text is indented 10 spaces.

If space is a non-empty string, such as '\t', the return-value text is indented with the characters in the string at each level.

If space is a string that is longer than 10 characters, the first 10 characters are used.
复制代码
复制代码
复制代码

 

那我们现在就可以把函数也序列化了

复制代码
复制代码
复制代码
var s=JSON.stringify(json, function(key, val) {
  if (typeof val === 'function') {
    return val + '';
  }
  return val;
});


"{"name":"json","getName":"function (){\n     return this.name;   \n  }"}"
复制代码
复制代码
复制代码

 

ok现在我们已经成功的序列化带function的json对象了,接下来如何还原它呢?

直接JSON.parse(s)?  骚年你还是太年轻了。

JSON.parse(s)输出的是

其实JSON.parse和JSON.stringify一样也有些其他参数

复制代码
复制代码
复制代码
JSON.parse(text [, reviver])

text
  Required. A valid JSON string.
reviver
  Optional. A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is. For each member, the following occurs:
If reviver returns a valid value, the member value is replaced with the transformed value.
If reviver returns the same value it received, the member value is not modified.
If reviver returns null or undefined, the member is deleted.
复制代码
复制代码
复制代码

 

那么我们就可以这么来还原json对象

复制代码
复制代码
复制代码
JSON.parse(s,function(k,v){

  if(v.indexOf&&v.indexOf('function')>-1){

     return eval("(function(){return "+v+" })()")

  }

  return v;

});
复制代码
复制代码
复制代码

输出:

通过这种方式我们也可以完全深拷贝一个json对象了。

 

 

转自:https://www.cnblogs.com/sparkbj/p/8203343.html

posted @   Sameen  阅读(518)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示