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. [NOI 2016]国王饮水记

    Description 题库链接 给出 \(n\) 个水杯,每个水杯装有不同高度的水 \(h_i\) ,每次可以指定任意多水杯用连通器连通后断开,问不超过 \(k\) 次操作之后 \(1\) 号水杯的 ...

  2. Webscoket

    websocket: http://blog.csdn.net/xiaoping0915/article/details/78754482    很好的讲解了websocket ,还有一个小例子 ht ...

  3. JSON跨域解决方案收集

    最近面试问的挺多的一个问题,就是JavaScript的跨域问题.在这里,对跨域的一些方法做个总结.由于浏览器的同源策略,不同域名.不同端口.不同协议都会构成跨域:但在实际的业务中,很多场景需要进行跨域 ...

  4. 10.C#知识点:操作XML

    知识点目录==========>传送门 XML是什么就不用说了文本标记语言. 主要纪录如何对XML文件进行增删改查. Xml的操作类都存在System.xml命名空间下面. 应用型的直接上代码 ...

  5. Android - Dagger2 使用和原理

    Dagger2从入门到放弃再到恍然大悟 http://www.jianshu.com/p/cd2c1c9f68d4 http://www.jianshu.com/p/39d1df6c877d http ...

  6. Android - 注解

    原理: http://www.cnblogs.com/Fndroid/p/5354644.html http://www.jianshu.com/p/28edf5352b63 开源库: ButterK ...

  7. 关于chrome 插件PageMonitor 安装及使用步骤

    首先是安装: 第一步:打开谷歌浏览器的设置界面(如果没有谷歌浏览器需要下载安装下) 然后 点击左侧扩展程序:出现如下图 然后把附件中Page_Monitor_Chrome.crx文件托到扩展程序界面, ...

  8. HDU3622(二分+2-SAT)

    Bomb Game Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  9. python-状态模式

    源码地址:https://github.com/weilanhanf/PythonDesignPatterns 说明: 在软件开发过程中,各种应用程序可能会根据不同的情况做出不同的处理.最直接的方案就 ...

  10. 关于子元素的margin-top溢出和元素浮动对父元素高度影响解决方案

    以下是个人学习笔记,仅供学习参考. 1.关于子元素的margin-top作用在无margin-top-border的父元素上导致子元素的margin-top溢出问题. 在给没有margin-top-b ...