json当简单的map用(只能放字符串键值对)

/**
 * 
 *说明:只支持放字符串键值对
 * 用法:
	 var json=simpleJson();
	 json.put("key1","value1");
	 json.put("key2","value2");
	 var returnJsonObj=json.get();
	 var returnJsonStr=json.get("str"); 
 */
function simpleJson()
{
	this.jsonStr="{";
	//放入key与value
	this.put=function (key,value)
	{
		//防止put,get交叉操作拼接会出错,即put以后直接get,而后又put,要去掉拼接最后的"}"
		var hasRight=this.jsonStr.substring(this.jsonStr.length-1,this.jsonStr.length)=="}"?true:false;
		if(hasRight)
			this.jsonStr=this.jsonStr.substring(0,this.jsonStr.length-1)+",";
		//json敏感字符过滤
		value=this.jsonFilter(value);
		this.jsonStr+="'"+key+"'"+":"+"'"+value+"'"+",";
	};
	//get()获取拼接好的json对象,
	//get("str"),将返回字符串(即未eval)
	this.get=function(str)
	{
		//是否有put过
		if(this.jsonStr.length>1)
			this.jsonStr=this.jsonStr.substring(0,this.jsonStr.length-1);
		this.jsonStr+="}";
		//返回拼接的字符串
		if(str=="str")
			return this.jsonStr;
		//返回json对象
		return eval("("+this.jsonStr+")");
	};
	//json敏感字符过滤
	this.jsonFilter=function(v) 
	{
		//先过滤掉这个转义"\"字符
		v=v.replace(/\\/g,"\\\\");
		//下面才能正常过滤,不然转义会有问题
		v=v.replace(/'/g,"\\'");
		v=v.replace(/\n/g,"\\\\n").replace(/\r/g,"\\\\r");
		v=v.replace(/\t/g,"\\\\t").replace(/\f/g,"\\\\f");
		return v;
	};
}

你可能感兴趣的:(js,json,map)