`
lan13217
  • 浏览: 496284 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

js Objec->String

 
阅读更多
function obj2string(o){
	var r=[];
	if(typeof o=="string"){
		return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
	}
	if(typeof o=="object"){
		if(!o.sort){
			for(var i in o){
				r.push(i+":"+obj2string(o[i]));
			}
			if(!!document.all&&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){
				r.push("toString:"+o.toString.toString());
			}
			r="{"+r.join()+"}";
		}else{
			for(var i=0;i<o.length;i++){
				r.push(obj2string(o[i]))
			}
			r="["+r.join()+"]";
		} 
		return r;
	} 
	return o.toString();
}

function writeObj(obj){
	var description = "";
	for(var i in obj){  
		var property=obj[i];  
		description+=i+" = "+property+"\n"; 
	}  
	alert(description);
}



Extjs obj->json
myobj = Ext.decode("{a:\"a\",b:\"b\"}")

Extjs json->obj
myobj = Ext.encode(myobj)


Extjs decode
function (json){return eval("("+json+")")} 



Extjs encode
function (o) {
	if (typeof o == "undefined" || o === null) {
		return "null"
	} else {
		if (Ext.isArray(o)) {
			return encodeArray(o)
		} else {
			if (Ext.isDate(o)) {
				return encodeDate(o)
			} else {
				if (typeof o == "string") {
					return encodeString(o)
				} else {
					if (typeof o == "number") {
						return isFinite(o) ? String(o) : "null"
					} else {
						if (typeof o == "boolean") {
							return String(o)
						} else {
							var a = ["{"],
							b,
							i,
							v;
							for (i in o) {
								if (!useHasOwn || o.hasOwnProperty(i)) {
									v = o[i];
									switch (typeof v) {
									case "undefined":
									case "function":
									case "unknown":
										break;
									default:
										if (b) {
											a.push(",")
										}
										a.push(this.encode(i), ":", v === null ? "null" : this.encode(v));
										b = true
									}
								}
							}
							a.push("}");
							return a.join("")
						}
					}
				}
			}
		}
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics