将javascript对象转换成json字符串,扩展了Object的方法。
资源下载地址: http://download.csdn.net/detail/w172087242/9575125
下面是代码:
/**
* 对js对象的json序列化
* @author littlehow
* @time 2016/7/13 11:49
*/
var littlehow = {
S : function(){
this._arr = [];
this.add = function(s){
this._arr.push(s);
return this;
}
this.removeLastAdd = function(){
this._arr.pop();
return this;
}
this.toString = function(s) {
return this._arr.join(s || "");
}
},
getS : function(obj){
if(obj === undefined) return "";
if(typeof obj == "string"){
return '"' + obj + '"';
} else if(typeof obj == "date"){//如果不想转换成毫秒数,可以改写这里
return obj.getTime();
} else {
return obj;
}
}
}
Object.prototype.forJsonString = function(){
if(typeof this == "function") return "{}";
var sb = new littlehow.S();
if(this.constructor == Array) {//处理数组
if(this.length == 0) return "[]";
sb.add("[");
for(var i = 0, len = this.length; i < len; i ++){
var v = this[i];
if(typeof v == "object") v = v.forJsonString();
else v = littlehow.getS(v);
sb.add(v).add(", ");
}
return sb.removeLastAdd().add("]").toString();
}else if(this.constructor == Date){<span style="font-family: Arial, Helvetica, sans-serif;">//如果不想转换成毫秒数,可以改写这里</span>
return this.getTime();
}else if(typeof this == "object"){
sb.add("{");
for(var i in this){
var v = this[i];
var type = typeof v;
if(type == "function"){
continue;
} else{
if(typeof v == "object") v = v.forJsonString();
else v = littlehow.getS(v);
sb.add('"').add(i).add('" : ').add(v).add(", ");
}
}
return sb.removeLastAdd().add("}").toString();
} else if(typeof this == "string"){
return '"' + this + '"';
} else if(typeof this == "date"){
return this.getTime();
} else {
return this;
}
}
html调用代码示例:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json test</title>
<script type="text/javascript" src="selfJson.js"></script>
<script type="text/javascript">
//数组
var arr = [123, "455", new Object(), new Date()];
arr[2].name = "littlehow";
arr[2].age = 28;
arr[2].birth = new Date();
arr[2].son = new Object();
arr[2].son.name = "herry";
arr[2].son.age = 3;
arr[2].son.birth = new Date(1313131313);
console.log(arr.forJsonString());
//普通对象
function Person(name, age, birth) {
this.name = name;
this.age = age;
this.birth = birth;
}
var obj = {};
obj.hobby = ["one", "two", "three", "four"];
obj.friend = [new Person("小红", 23, "1993-08-09"), new Person("小李", 22, new Date())];
obj.name = "littlehow";
obj.now = new Date();
obj.length = 3;
obj.运动 = "打游戏";
obj.add = function(a, b){
return a + b;
}
obj.toString = function(){
return this.name;
}
console.log(obj.forJsonString());
</script>
</head>
<body>
</body>
</html>