[JavaScript]JSONçãªãã³ããã¨ãé¢æ°ãä½ã£ã¦ã¿ã
IEã§ãããã¯ãããã¨Firebugã¿ããã«ãªãã¸ã§ã¯ããå±éãã¦ã¿ããã£ãã®ã§ä½ã£ã¦ã¿ãã
ç¹å¾´ã¯ã
- ã¤ã³ãã³ãã®ãªã³ãªãã
- ããããã£(ãã¼)ã®ã½ã¼ãã®ãªã³ãªã
- é¢æ°ã®ã½ã¼ã¹è¡¨ç¤ºåãæ¿ã
- å¤æ°(ãªãã¸ã§ã¯ã)ãåç §ãæ·±ãå ´åã®å¶é(å¶éãè¶ ããã¨throwããã)
ã³ã¼ã
var dumpJson = function(v, opts){ var _opts={ksort:false, indent:false, funcsrc:false, undefined2str:false, maxDepth:10}; for(var k in opts) _opts[k]=opts[k]; var d=parseInt(_opts.maxDepth); _opts.maxDepth=(d>0)?(d<100)?d:100:1; var f1=(!!_opts.indent)?function(d){ for(var s='\n', i=0; i<=d; i++) s+=' '; return s }:function(){ return ''; }; var f2ps=[[/\\/g,"\\\\"],[/\n/g,"\\n"],[/\r/g ,"\\r"],[/\t/g,"\\t"],[/(")/g,"\\$1"]]; var f2=function(v){ for(var i=0;i<f2ps.length;i++) v=v.replace.apply(v,f2ps[i]); return v; } var fn=function(v,d){ if(d>=_opts.maxDepth) throw 'depth '+_opts.maxDepth+' orver error.'; if(null===v) return 'null'; switch(typeof v){ case 'undefined': return (!!_opts.undefined2str)?'"undefined"':'null'; case 'boolean': return v?'true':'false'; case 'function': v=(!!_opts.funcsrc)?v.toSource():'function()'; case 'string': return '"'+f2(v)+'"'; case 'object': var s=[]; if(v instanceof Array){ for(var i=0; i<v.length; i++) s.push(fn(v[i],d+1)); return '['+f1(d)+s.join(','+f1(d))+f1(d-1)+']'; } var ks=[]; for(var k in v) ks.push(k); if(!!_opts.ksort) ks.sort(); for(var i=0; i<ks.length; i++) s.push(fn(ks[i],d+1)+':'+fn(v[ks[i]],d+1)); return '{'+f1(d)+s.join(','+f1(d))+f1(d-1)+'}'; } return v; } return fn(v,0); };
使ãæ¹
第ä¸å¼æ°ã«ãã³ããããå¤æ°ã第äºå¼æ°ã«ãªãã·ã§ã³ã
ãªãã·ã§ã³ã¯ãã¤ã³ãã³ã[indent]ãããããã£(ãã¼)ã®ã½ã¼ã[ksort]ãfunctionã®å ´åã®åãæ¿ã[funcsrc]ãå¤æ°ã循ç°åç
§ã ã£ãå ´åã®æ大深度[maxDepth]
var v={ aaa:'AA\nA', bbb:['01', '02', '03', 4, true, null ], '1':{ '2':{ '3':{ '4':{ '5':'aaa' } } } } }; v['ff']=function(){alert('aa');}; try{ console.log(dumpJson(v,{indent:true})); }catch(e){ console.log(e); }
å®è¡çµæ
{ "aaa":"AA\nA", "bbb":[ "01", "02", "03", 4, true, null ], "1":{ "2":{ "3":{ "4":{ "5":"aaa" } } } }, "ff":"function()" }
ã¡ã¢
åãåããä½ã£ã¦ã¿ããã©maxDepthã¯é¢æ°ã渡ãã¦throwããã¨ãreturnããã¨ãåºæ¥ãããã«ããã»ããè¯ãã£ãããã
evalé¢æ°ã使ãã°ç°¡åã«JSONæååãã¤ã³ãã³ãã§ãããªã