jQuery处理json数据返回数组和输出的方法
本文实例讲述了jQuery处理json数据返回数组和输出的方法。分享给大家供大家参考。具体实现方法如下:
/*printthejsonobject * *$("selector").print_r_json(json,opts):returnformattedstring(andprint) *sprint_r_json:justreturnthestring; *print_r_json:returntheformattedstringandprintjsondata *contribute明河 * *authiorichina * *example: *3waystouseit *<scriptlanguage="javascript"> *$("selector").print_r_json({"a":"aa","d":{"ef":{"a":"d","d":["a","b"]},"ed":"dd"},"g":"g"},{if_print:true,return_array:true}); *document.write($.sprint_r_json({"a":"aa","d":{"ef":{"a":"d","d":["a","b"]},"ed":"dd"},"g":"g"})); *$.print_r_json({"a":"aa","d":{"ef":{"a":"d","d":["a","b"]},"ed":"dd"},"g":"g"}); *</script> * */ $.fn.print_r_json=function(json,options){ if(typeof(json)!="object")returnfalse; varopts=$.extend({},$.fn.print_r_json.defaults,options); vardata=''; if(opts.if_print) { data=$.sprint_r_json(json) $(this).html('<divstyle="font-weight:bold">'+(opts.return_array?'Array':'JSON-DATA')+'</div>'+data); } if(opts.array) { return$.json_to_array(json); } returndata; }; $.fn.print_r_json.defaults= { if_print:false,//ifprintorjustreturnformattedstring return_array:true//returnanArray }; $.extend({ print_r_json:function(json) { if(typeof(json)=="object") { vartext='<divstyle="font-weight:bold;">{</div><divstyle="margin-left:25px;">'; document.write('<divstyle="font-weight:bold;">{</div><divstyle="margin-left:25px;">'); for(varpinjson) { if(typeof(json[p])=="object") { document.write('<div>["'+p+'"]=>'); text+='<div>["'+p+'"]=>'+$.print_r_json(json[p])+'</div>'; document.write('</div>'); } else { text+='<div>['+((/^\d+$/).test(p)?p:('"'+p+'"'))+']=>"'+json[p]+'"</div>'; document.write('<div>['+p+']=>'+json[p]+'</div>'); } } text+='</div><divstyle="font-weight:bold;">}</div>'; document.write('</div><divstyle="font-weight:bold;">}</div>'); return(text); } else { document.write(json); return(json); } }, sprint_r_json:function(json) { if(typeof(json)=="object") { vartext='<divstyle="font-weight:bold;">{</div><divstyle="margin-left:25px;">'; for(varpinjson) { if(typeof(json[p])=="object") { text+='<div>["'+p+'"]=>'+$.sprint_r_json(json[p])+'</div>'; } else { text+='<div>['+((/^\d+$/).test(p)?p:('"'+p+'"'))+']=>"'+json[p]+'"</div>'; } } text+='</div><divstyle="font-weight:bold;">}</div>'; return(text); } else { return(json); } }, json_to_array:function(json) { if(typeof(json)=="object") { vartext=newArray(); for(varpinjson) { if(typeof(json[p])=="object") { text[p]=$.json_to_array(json[p]); } else { text[p]=json[p]; } } return(text); } else { return(json); } } });
希望本文所述对大家的jQuery程序设计有所帮助。