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 ' ' 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, ' $1 ');
  25. // add newline before and after square brackets
  26. reg = /([[]])/g;
  27. json = json.replace(reg, ' $1 ');
  28. // add newline after comma
  29. reg = /(\,)/g;
  30. json = json.replace(reg, '$1 ');
  31. // remove multiple newlines
  32. reg = /( )/g;
  33. json = json.replace(reg, ' ');
  34. // remove newlines before commas
  35. reg = / \,/g;
  36. json = json.replace(reg, ',');
  37. // optional formatting...
  38. if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
  39. reg = /: {/g;
  40. json = json.replace(reg, ':{');
  41. reg = /: [/g;
  42. json = json.replace(reg, ':[');
  43. }
  44. if (options.spaceAfterColon) {
  45. reg = /:/g;
  46. json = json.replace(reg, ':');
  47. }
  48. $.each(json.split(' '), 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 + ' ';
  65. pad += indent;
  66. });
  67. return formatted;
  68. };

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






原文地址:https://www.cnblogs.com/huangtailang/p/00dea6d9cc66eede7ab840d4db634634.html