javascript格式化json显示

 
  
  1. // Example usage: http://jsfiddle.net/q2gnX/
  2. var formatJson = function(json, options) {
  3. var reg = null,
  4. formatted = '',
  5. pad = 0,
  6. PADDING = ' '; // one can also use '\t' or a different number of spaces
  7. // optional settings
  8. options = options || {};
  9. // remove newline where '{' or '[' follows ':'
  10. options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
  11. // use a space after a colon
  12. options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
  13. // begin formatting...
  14. if (typeof json !== 'string') {
  15. // make sure we start with the JSON as a string
  16. json = JSON.stringify(json);
  17. } else {
  18. // is already a string, so parse and re-stringify in order to remove extra whitespace
  19. json = JSON.parse(json);
  20. json = JSON.stringify(json);
  21. }
  22. // add newline before and after curly braces
  23. reg = /([\{\}])/g;
  24. json = json.replace(reg, '\r\n$1\r\n');
  25. // add newline before and after square brackets
  26. reg = /([\[\]])/g;
  27. json = json.replace(reg, '\r\n$1\r\n');
  28. // add newline after comma
  29. reg = /(\,)/g;
  30. json = json.replace(reg, '$1\r\n');
  31. // remove multiple newlines
  32. reg = /(\r\n\r\n)/g;
  33. json = json.replace(reg, '\r\n');
  34. // remove newlines before commas
  35. reg = /\r\n\,/g;
  36. json = json.replace(reg, ',');
  37. // optional formatting...
  38. if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
  39. reg = /\:\r\n\{/g;
  40. json = json.replace(reg, ':{');
  41. reg = /\:\r\n\[/g;
  42. json = json.replace(reg, ':[');
  43. }
  44. if (options.spaceAfterColon) {
  45. reg = /\:/g;
  46. json = json.replace(reg, ':');
  47. }
  48. $.each(json.split('\r\n'), function(index, node) {
  49. var i = 0,
  50. indent = 0,
  51. padding = '';
  52. if (node.match(/\{$/) || node.match(/\[$/)) {
  53. indent = 1;
  54. } else if (node.match(/\}/) || node.match(/\]/)) {
  55. if (pad !== 0) {
  56. pad -= 1;
  57. }
  58. } else {
  59. indent = 0;
  60. }
  61. for (i = 0; i < pad; i++) {
  62. padding += PADDING;
  63. }
  64. formatted += padding + node + '\r\n';
  65. pad += indent;
  66. });
  67. return formatted;
  68. };

使用方法:
 
   
  1. var json={"name":"HTL","sex":"男","age":"24"};
  2. console.log(formatJson(json));

//该代码片段来自于: http://www.sharejs.com/codes/javascript/5452





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值