【问题标题】:Javascript object to formatted stringJavascript 对象到格式化字符串
【发布时间】:2012-10-08 15:48:40
【问题描述】:

如何将对象输出为带有格式的可读字符串(结构类似于<pre>)?

不可能有 jQuery。

使用console.log,我的对象看起来像这样。

Object
   title: "Another sting"
   type: "tree"
   options: Object
      paging: "20"
      structuretype: "1"
   columns: Object
      ...
   description: "This is a string"
   ...

将其转换为结构化字符串的最佳方法是什么?

我的尝试:

我尝试使用stringify() 来获取 JSON 结构。然后我可以编写自己的解析器,但也许已经有任何实现了?

【问题讨论】:

标签: javascript json object


【解决方案1】:

JSON.stringify 包含一个格式化参数:

JSON.stringify(value[, replacer [, space]])

空格参数可用于控制最终字符串中的间距。如果它是一个数字,则字符串化中的连续级别将由这么多空格字符(最多 10 个)缩进。如果它是一个字符串,连续的级别将由这个字符串(或它的前十个字符)缩进。

使用制表符模仿标准的漂亮打印外观

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

这是否足以满足您的需要?例如。试试:

 JSON.stringify( object, null, 2 );

否则,http://code.google.com/p/google-code-prettify/ 是一个独立的 JSON 到 HTML 的漂亮打印机。我相信被 stackoverflow 和谷歌代码使用。

【讨论】:

  • 谢谢你的解决方案,我不知道空间参数。事实上,我可以将它与删除不需要的字符 {}" 结合使用。
【解决方案2】:

同时我想出了这个功能,也许有人可以使用它:

addIndent: function(nSpaces) {
         var strOutput = '';
         for(var i = 0; i < nSpaces; i++) {
            strOutput += '--';
         }
         return strOutput; 
      }

parseObjToStr: function(oObject, nLevel) {
         var that = this;
         var strOutput = '';
         nLevel = nLevel || 0;

         for(var oEl in oObject) {
            if(typeof oObject[oEl] === 'object' || Object.prototype.toString.call( oObject[oEl] ) === '[object Array]') 
            {
               strOutput += that.addIndent(nLevel) + oEl + "<br />";
               strOutput += that.parseObjToStr( oObject[oEl], nLevel+1);
            } 
            else 
            {
               strOutput += that.addIndent(nLevel) + oEl + " = " + oObject[oEl] + "<br />";
            }
         }
         return strOutput;
      }

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 2013-04-21
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 2012-10-11
    • 2012-07-09
    相关资源
    最近更新 更多