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

将js变量转换为json格式字符串
function printVar(v)
{
	if(v==null) return 'null';
	var type = typeof(v);
	var rtn = '';
	switch(type)
	{
		case 'boolean':
			if(v)
				rtn='true';
			else
				rtn='false';
			break;
		case 'object':
			var i = 0;
			if(typeof(v.length)=='undefined')
			{
				rtn = '{';
				for(var x in v)
				{
					if(i==0)
						rtn+=x+':'+printVar(v[x]);
					else
						rtn+=','+x+':'+printVar(v[x]);
					i++;
				}
				rtn += '}';
			}else{
				rtn = '[';
				for(var i=0;i<v.length;i++)
				{
					if(i==0)
						rtn+=printVar(v[i]);
					else
						rtn+=','+printVar(v[i]);
				}
				rtn += ']';
			}
			break;
		case 'string':
			rtn = '"'+v+'"';
			break;
		case 'number':
		default:
			rtn = v;
	}
	return rtn;
}