设为首页收藏本站
开启辅助访问
切换到宽版

创星网络[分享知识 传递快乐]

 找回密码
 立即注册

QQ登录

只需一步,快速开始

用新浪微博登录

只需一步,快速搞定

搜索
查看: 3811|回复: 0
打印 上一主题 下一主题

json format:json数据格式化

[复制链接]

我玩的应用:

跳转到指定楼层
楼主
发表于 2012-12-13 23:19:06 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
json数据格式化(json format)实现方法,直接上代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">


  3. <body>
  4. <div id="show_ajax"></div>

  5. <textarea cols="100" rows="5" id="show_ajax2"></textarea>

  6. <script>
  7. /*
  8. json-format v.1.1
  9. http://github.com/phoboslab/json-format

  10. Released under MIT license:
  11. http://www.opensource.org/licenses/mit-license.php
  12. */

  13. (function(window) {
  14. var p = [],
  15. push = function( m ) { return '\\' + p.push( m ) + '\\'; },
  16. pop = function( m, i ) { return p[i-1] },
  17. tabs = function( count ) { return new Array( count + 1 ).join( '\t' ); };

  18. window.JSONFormat = function( json ) {
  19. p = [];
  20. var out = "",
  21. indent = 0;

  22. // Extract backslashes and strings
  23. json = json
  24. .replace( /\\./g, push )
  25. .replace( /(".*?"|'.*?')/g, push )
  26. .replace( /\s+/, '' );

  27. // Indent and insert newlines
  28. for( var i = 0; i < json.length; i++ ) {
  29. var c = json.charAt(i);

  30. switch(c) {
  31. case '{':
  32. case '[':
  33. out += c + "\n" + tabs(++indent);
  34. break;
  35. case '}':
  36. case ']':
  37. out += "\n" + tabs(--indent) + c;
  38. break;
  39. case ',':
  40. out += ",\n" + tabs(indent);
  41. break;
  42. case ':':
  43. out += ": ";
  44. break;
  45. default:
  46. out += c;
  47. break;
  48. }
  49. }

  50. // Strip whitespace from numeric arrays and put backslashes
  51. // and strings back in
  52. out = out
  53. .replace( /\[[\d,\s]+?\]/g, function(m){ return m.replace(/\s/g,''); } )
  54. .replace( /\\(\d+)\\/g, pop ) // strings
  55. .replace( /\\(\d+)\\/g, pop ); // backslashes in strings

  56. return out;
  57. };
  58. })(window);


  59. var someJSONString  = '{ "count": 5, "time_interval": 5 }'
  60. var formattedJSONString = JSONFormat( someJSONString );

  61. document.getElementById("show_ajax2").innerHTML =formattedJSONString;

  62. </script>
  63. </body>
  64. </html>
复制代码

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 转播转播 分享分享 分享淘帖
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|创星网络 ( 苏ICP备11027519号|网站地图  

GMT+8, 2024-5-2 20:07 , Processed in 0.081059 second(s), 24 queries .

Powered by Discuz! X3

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表