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对象了。

参考资料:http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx

带有function的JSON对象的序列化与还原的更多相关文章

  1. 利用JavaScriptSerializer类 进行Json对象的序列化和反序列化和过滤

    项目下载:JavaScriptSerializer_对JSON对象序列化与反序列化及过滤器 利用<JavascriptSerializer类> 进行Json对象的序列化和反序列化 1. 首 ...

  2. JavaScript - 问题集 - 含function的json对象与json字符串之间相互转换

    基本的转换为:JSON.parse与JSON.stringify. 但是json数据中含function,则转换后,function会丢失,如: var json={ test:'test', log ...

  3. return Json对象时序列化错误

    当要序列化的表与另一个表是一对多的关系是,表1序列化时会找到另一个表2关联的字段,会将另一个表2进行序列化,然后表2中也有一个字段与表1关联,这样序列化就会产生循环序列化. 在网上进行搜索,其中大多数 ...

  4. function的json对象转换字符串与字符串转换为对象的方法

    // json对象转换成字符串var str = JSON.stringify(json, function(key, val) { if (typeof val === 'function') { ...

  5. 利用<JavascriptSerializer类> 进行Json对象的序列化和反序列化

    1. 首先, JavascriptSerializer类所在名空间: using System.Web.Script.Serialization; 2. 相关的3篇文章, 标记下: 使用JavaScr ...

  6. javascript对json对象的序列化与反序列化

    首先引入一个json2.js.官方的地址为:https://github.com/douglascrockford/JSON-js 这里为了方便我直接贴上源代码 /* json2.js 2013-05 ...

  7. js实现对json数据的序列化(兼容ie6以上浏览器)

    /** * 增加对JSON数据的序列化方法, * 主要用于IE6.7不支持JSON对象的浏览器 */ var xue = xue || {};xue.json = xue.json || {}; xu ...

  8. ng json格式的序列化和反序列化

    ng中自带方法 angular.toJson 序列化angular.fromJson 反序列化 结果: 代码: <!DOCTYPE html> <html ng-app=" ...

  9. javascript中字符串格式json如何转化成json对象

    什么是JSON JSON(JavaScript Object Notation)是一种优美的JavaScript对象创建方法.JSON也是一种轻量级数据交换格式.JSON非常易于人阅读与编写,同时利于 ...

随机推荐

  1. Spring基础(2):bean顺序创建

    public class Person{ public Person(){ System.out.println("Person person person ..."); } } ...

  2. 链接正常但IE浏览器无法显示网页的几种情况

    一.感染病毒木马所致 这种情况往往表现在打开IE时,在IE界面的左下框里提示:正在打开网页,但一直无响应. 右击任务栏/任务管理器/进程,查看.如果CPU占用率100%,可以断定是感染了病毒,这时要查 ...

  3. Sql 四大排名函数(ROW_NUMBER、RANK、DENSE_RANK、NTILE)(转载)

    Sql 四大排名函数(ROW_NUMBER.RANK.DENSE_RANK.NTILE)简介   排名函数是Sql Server2005新增的功能,下面简单介绍一下他们各自的用法和区别.我们新建一张O ...

  4. 彻底理解ReentrantLock

    5.ReentrantLock的介绍 ReenTrantLock重入锁,是实现Lock接口的一个类,也是在实际编程中使用频率很高的一个锁,支持重入性,表示能够对共享资源能够重复加锁,即当前线程获取该锁 ...

  5. Mock session,cookie,querystring in ASB.NET MVC

    写测试用例的时候经常发现,所写的功能需要Http上下文的支持(session,cookie)这类的. 以下介绍2种应用场景. 用于控制器内Requet获取参数 控制器内的Requet其实是控制器内的属 ...

  6. mongdb基本操作和更新操作

    1.创建数据库 use hqj 不会真正的创建db,只有insert之后才会创建2.查看数据库show dbs3.插入文档db.hqj.insert({name:'111'})4.查看所有的文档sho ...

  7. Pupu(hdu3003)数论

    Pupu Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submi ...

  8. js文字滚动效果

    function (global) { var logo = document.getElementById('logo'); var text = document.createTextNode(' ...

  9. vue input输入框联想

    以下是示例,样式可以自己修改.最后是效果图,其实也挺简单的,主要是用了watch监控input输入值的变化,如果数据是请后端请求可以,先请求数据. <template> <div c ...

  10. Dynamics CRM2016 如何删除Word/Excel Templates

    创建模板的方式有两种,一种是创建个人级别的模板,如下面这种创建一个excel的模板 一种是在设置-模板中创建,但这需要管理员权限,从下图中可以看出个人级的模板在设置中是看不到的 那就涉及到一个问题了, ...