javascript格式化json數據顯示

  1. 函數實現

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

函數使用

  • 參數 newlineAfterColonIfBeforeBraceOrBracket 標識大括號是跟在後面還是重起一行

    • formatJson({a: {b : 1}, c: 2})

      1. "
      2. {
      3. "a": {
      4. "b": 1
      5. },
      6. "c": 2
      7. }
      8. "
    • formatJson({a: {b : 1}, c: 2}, {newlineAfterColonIfBeforeBraceOrBracket: true})

      1. "
      2. {
      3. "a":
      4. {
      5. "b": 1
      6. },
      7. "c": 2
      8. }
      9. "

JSON 展示

 

  • div + white-space: pre;
  • textarea
    1. $("#share")[0].style.height ="0"
    2. $("#share")[0].style.height = $("#share")[0].scrollHeight +'px'
發佈了29 篇原創文章 · 獲贊 10 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章