转换js变量为json格式的字符串,代码如下:
<script> //转换变量 js变量->json //by www.jb200.com 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; } </script>