日期:2014-05-16  浏览次数:20380 次

模拟原生的JSON.stringify方法

解决ie6、ie7没有原生js对象转JSON字符串的问题

JSON1.stringify1 使用函数递归调用方式,操作的js对象受限于浏览器的堆栈大小(大概几千或一万)

JSON1.stringify2 使用数组栈方式,速度快,不受限于浏览器的堆栈大小,受限于数组的大小(可忽略)

?

和原生JSON.stringify的区别:

  1. 保留了undefined的值(无法兼容后台java等不支持undefined的语言)
  2. 未支持replacer等后续参数
  3. 未支持对象的toJSON方法,只支持基本的undefined、null、number、string、boolean类型,以及包含这些类型的数组和键值对对象

?

var JSON1 = {
	stringify2 : function (jsObj) { //使用数组栈方式
		var stack1 = [];
		var stack2 = [];
		var process = function(obj){
			if(obj && typeof obj == "object"){
				return obj;
			}else if(typeof obj == "string"){
				return "\"" + obj.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
			}else{
				return obj + "";
			}
		}
		stack1.push(process(jsObj));
		
		while(stack1.length){
			var o = stack1.pop();
			if(typeof o == "object"){
				/*
				var isArray = o instanceof Array;
				stack1.push(isArray ? "[" : "{");
				var i = null;
				if(isArray){
					for(i = 0; i < o.length; i++){
						stack1.push(process(o[i]));
						stack1.push(",");
					}
				}else{
					for(i in o){
						stack1.push("\"" + i + "\":");
						stack1.push(process(o[i]));
						stack1.push(",");
					}
				}
				if(i){//移除最后一个无效的逗号[,]
					stack1.pop();
				}
				stack1.push(isArray ? "]" : "}");
				*/
				var i = null;//必须显示的设置为null,防止空对象时保留了上一次循环的结果
				if(o instanceof Array){
					stack1.push("[");
					for(i = 0; i < o.length; i++){
						stack1.push(process(o[i]));
						stack1.push(",");
					}
					if(i){//移除最后一个无效的逗号[,]
						stack1.pop();
					}
					stack1.push("]");
				}else{
					stack1.push("{");
					for(i in o){
						stack1.push("\"" + i + "\":");
						stack1.push(process(o[i]));
						stack1.push(",");
					}
					if(i){//移除最后一个无效的逗号[,]
						stack1.pop();
					}
					stack1.push("}");
				}
			}else{//字符串(已经处理)
				stack2.unshift(o);
			}
		}
		return stack2.join("");
	},
	stringify1 : function (jsonObj) { //使用函数递归调用的方法
		var jsonBuffer = [];
		var type = typeof jsonObj;//undefined,boolean,number,string,object
		if(type === "object"){
			if(jsonObj === null){
				jsonBuffer.push(jsonObj + "");
			}else{
				if(jsonObj instanceof Array){
					jsonBuffer.push("[");
					for(var i = 0; i < jsonObj.length; i++){
						jsonBuffer.push(JSON1.stringify1(jsonObj[i]));
						jsonBuffer.push(",");
					}
					if(i){
						jsonBuffer.pop();//移除最后一个无效的逗号[,]
					}
					jsonBuffer.push("]");
				}else{
					jsonBuffer.push("{");
					for(var j in jsonObj){
						jsonBuffer.push("\"" + j + "\":" + JSON1.stringify1(jsonObj[j]));
						jsonBuffer.push(",");
					}
					if(j){
						jsonBuffer.pop();//移除最后一个无效的逗号[,]
					}
					jsonBuffer.push("}");
				}
			}
		}else if(type == "string"){
			jsonBuffer.push("\"" + jsonObj.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"");
		}else{
			jsonBuffer.push(jsonObj + "");
		}
		return jsonBuffer.join("");
	}
}

?

?