JavaScript数据格式化/漂亮打印机

JavaScript数据格式化/漂亮打印机,javascript,debugging,json,Javascript,Debugging,Json,我试图找到一种方法,以人类可读的形式将JavaScript数据结构打印出来,以便调试 我有一个相当大和复杂的数据结构存储在JS中,我需要编写一些代码来操作它。为了弄清楚我在做什么以及哪里出错,我真正需要的是能够看到整个数据结构,并在通过UI进行更改时对其进行更新 除了找到一种将JavaScript数据结构转储到人类可读字符串的好方法之外,所有这些我都可以自己处理。JSON可以,但它确实需要良好的格式和缩进。我通常会使用Firebug优秀的DOM转储功能来实现这一点,但我确实需要能够立即查看整个结

我试图找到一种方法,以人类可读的形式将JavaScript数据结构打印出来,以便调试

我有一个相当大和复杂的数据结构存储在JS中,我需要编写一些代码来操作它。为了弄清楚我在做什么以及哪里出错,我真正需要的是能够看到整个数据结构,并在通过UI进行更改时对其进行更新


除了找到一种将JavaScript数据结构转储到人类可读字符串的好方法之外,所有这些我都可以自己处理。JSON可以,但它确实需要良好的格式和缩进。我通常会使用Firebug优秀的DOM转储功能来实现这一点,但我确实需要能够立即查看整个结构,这在Firebug中似乎是不可能的。

Firebug
中,如果您只需
console.debug(“%o”,我的对象)
您可以在控制台中单击它并进入交互式对象资源管理器。它显示整个对象,并允许您展开嵌套对象。

包括一个prettyPrint()函数,该函数可能为您提供所需的内容。

如下所示:

var myArray = ['e', {pluribus: 'unum'}];
var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation...
[
  "e",
   {
      "pluribus": "unum"
   }
]
  var temp = Array.prototype.toJSON;
  delete Array.prototype.toJSON;
  $('result').value += JSON.stringify(profile_base, null, 2);
  Array.prototype.toJSON = temp;
js> pp({foo:"bar", baz: 1})
{ foo: "bar",
  baz: 1
}
js> var taco
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})
{ foo: "bar",
  baz: 
    [ 1,
      "taco",
      { blarg: "moo",
        mine: "craft"
      },
      null,
      undefined,
      {}
    ],
  bleep: 
    { a: null,
      b: undefined,
      c: []
    }
}
变量
text
如下所示:

var myArray = ['e', {pluribus: 'unum'}];
var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation...
[
  "e",
   {
      "pluribus": "unum"
   }
]
  var temp = Array.prototype.toJSON;
  delete Array.prototype.toJSON;
  $('result').value += JSON.stringify(profile_base, null, 2);
  Array.prototype.toJSON = temp;
js> pp({foo:"bar", baz: 1})
{ foo: "bar",
  baz: 1
}
js> var taco
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})
{ foo: "bar",
  baz: 
    [ 1,
      "taco",
      { blarg: "moo",
        mine: "craft"
      },
      null,
      undefined,
      {}
    ],
  bleep: 
    { a: null,
      b: undefined,
      c: []
    }
}


顺便说一句,这只需要JS文件——它可以与任何库一起工作,等等。

我编写了一个函数,以可读的形式转储JS对象,虽然输出没有缩进,但添加它应该不会太难:我从为Lua编写的函数中创建了这个函数(这要复杂得多)处理了这个缩进问题

以下是“简单”版本:

我将考虑对其进行一些改进。
注1:要使用它,请执行od=DumpObject(something)并使用od.dump。令人费解,因为我也希望len值(项目数)用于其他用途。让函数只返回字符串是很简单的。
注2:它不处理引用中的循环

编辑

我制作了缩进版本

function DumpObjectIndented(obj, indent)
{
  var result = "";
  if (indent == null) indent = "";

  for (var property in obj)
  {
    var value = obj[property];
    if (typeof value == 'string')
      value = "'" + value + "'";
    else if (typeof value == 'object')
    {
      if (value instanceof Array)
      {
        // Just let JS convert the Array to a string!
        value = "[ " + value + " ]";
      }
      else
      {
        // Recursive dump
        // (replace "  " by "\t" or something else if you prefer)
        var od = DumpObjectIndented(value, indent + "  ");
        // If you like { on the same line as the key
        //value = "{\n" + od + "\n" + indent + "}";
        // If you prefer { and } to be aligned
        value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
      }
    }
    result += indent + "'" + property + "' : " + value + ",\n";
  }
  return result.replace(/,\n$/, "");
}
使用递归调用在行上选择缩进,并通过在这一行之后切换注释行来设置括号样式

。。。我看到你自己编了一个版本,很好。游客们可以选择。

在菲略的带领下(非常感谢:),我最终写下了自己的作品,因为我无法让他做我想做的事。这是相当粗糙和准备,但它做的工作,我需要。谢谢大家的建议

我知道这不是一个精彩的代码,但不管它值多少钱,它就在这里。有人可能会发现它很有用:

// Usage: dump(object)
function dump(object, pad){
    var indent = '\t'
    if (!pad) pad = ''
    var out = ''
    if (object.constructor == Array){
        out += '[\n'
        for (var i=0; i<object.length; i++){
            out += pad + indent + dump(object[i], pad + indent) + '\n'
        }
        out += pad + ']'
    }else if (object.constructor == Object){
        out += '{\n'
        for (var i in object){
            out += pad + indent + i + ': ' + dump(object[i], pad + indent) + '\n'
        }
        out += pad + '}'
    }else{
        out += object
    }
    return out
}
//用法:转储(对象)
功能转储(对象、键盘){
变量缩进='\t'
如果(!pad)pad=''
var out=''
if(object.constructor==数组){
out+='[\n'

对于(var i=0;i这实际上只是对Jason Bunting的“Use Crockford's JSON.stringify”的一个评论,但我无法为这个答案添加评论

正如评论中所指出的,JSON.stringify与Prototype(www.prototypejs.org)库的关系不太好。但是,通过临时删除Prototype添加的Array.Prototype.toJSON方法,运行Crockford的stringify(),然后将其放回原样,可以让它们很好地结合在一起:

var myArray = ['e', {pluribus: 'unum'}];
var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation...
[
  "e",
   {
      "pluribus": "unum"
   }
]
  var temp = Array.prototype.toJSON;
  delete Array.prototype.toJSON;
  $('result').value += JSON.stringify(profile_base, null, 2);
  Array.prototype.toJSON = temp;
js> pp({foo:"bar", baz: 1})
{ foo: "bar",
  baz: 1
}
js> var taco
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})
{ foo: "bar",
  baz: 
    [ 1,
      "taco",
      { blarg: "moo",
        mine: "craft"
      },
      null,
      undefined,
      {}
    ],
  bleep: 
    { a: null,
      b: undefined,
      c: []
    }
}
变成

[
   [Window],
   [Document],
   {
      "1": "foo",
      "a": 5
   },
   /^[ab]+$/g,
   /x(.*?)z/gi,
   function alert( a ){
      [code]
   },
   function fn( a, b, c ){
      [code]
   },
   true,
   undefined,
   null,
   "Fri Feb 19 2010 00:49:45 GMT+0300 (MSK)",
   <body id="body" class="node"></body>,
   <div id="links">
]

我认为J.Buntings对使用JSON.stringify的响应也很好。另外,如果您碰巧使用YUI,您可以通过YUIs JSON对象使用JSON.stringify。在我的例子中,我需要转储到HTML,以便更容易地调整/剪切/粘贴PhiLho响应

function dumpObject(obj, indent) 
{
  var CR = "<br />", SPC = "&nbsp;&nbsp;&nbsp;&nbsp;", result = "";
  if (indent == null) indent = "";

  for (var property in obj)
  {
    var value = obj[property];

    if (typeof value == 'string')
    {
      value = "'" + value + "'";
    }
    else if (typeof value == 'object')
    {
      if (value instanceof Array)
      {
        // Just let JS convert the Array to a string!
        value = "[ " + value + " ]";
      }
      else
      {
        var od = dumpObject(value, indent + SPC);
        value = CR + indent + "{" + CR + od + CR + indent + "}";
      }
    }
    result += indent + "'" + property + "' : " + value + "," + CR;
  }
  return result;
}
函数转储对象(对象,缩进)
{
var CR=“
”,SPC=“”,result=“”; 如果(缩进==null)缩进=”; for(obj中的var属性) { var值=对象[属性]; 如果(值的类型=='string') { value=“””+value+“”; } else if(typeof value==“object”) { if(数组的值实例) { //只需让JS将数组转换为字符串! value=“[”+value+“]”; } 其他的 { var od=转储对象(值,缩进+SPC); 值=CR+indent+“{”+CR+od+CR+indent+“}”; } } 结果+=缩进+“'”+属性+“:“+值+”,“+CR; } 返回结果; }
我正在用
Rhino
编程,我对这里发布的任何答案都不满意。因此我编写了自己的漂亮打印机:

function pp(object, depth, embedded) { 
  typeof(depth) == "number" || (depth = 0)
  typeof(embedded) == "boolean" || (embedded = false)
  var newline = false
  var spacer = function(depth) { var spaces = ""; for (var i=0;i<depth;i++) { spaces += "  "}; return spaces }
  var pretty = ""
  if (      typeof(object) == "undefined" ) { pretty += "undefined" }
  else if ( typeof(object) == "boolean" || 
            typeof(object) == "number" ) {    pretty += object.toString() } 
  else if ( typeof(object) == "string" ) {    pretty += "\"" + object + "\"" } 
  else if (        object  == null) {         pretty += "null" } 
  else if ( object instanceof(Array) ) {
    if ( object.length > 0 ) {
      if (embedded) { newline = true }
      var content = ""
      for each (var item in object) { content += pp(item, depth+1) + ",\n" + spacer(depth+1) }
      content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
      pretty += "[ " + content + "\n" + spacer(depth) + "]"
    } else { pretty += "[]" }
  } 
  else if (typeof(object) == "object") {
    if ( Object.keys(object).length > 0 ){
      if (embedded) { newline = true }
      var content = ""
      for (var key in object) { 
        content += spacer(depth + 1) + key.toString() + ": " + pp(object[key], depth+2, true) + ",\n" 
      }
      content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
      pretty += "{ " + content + "\n" + spacer(depth) + "}"
    } else { pretty += "{}"}
  }
  else { pretty += object.toString() }
  return ((newline ? "\n" + spacer(depth) : "") + pretty)
}
我还将其作为将来可能需要进行的任何更改的参考发布。

对于Node.js,请使用:

util.inspect(object, [options]);

您可以使用以下

<pre id="dump"></pre>
<script>
   var dump = JSON.stringify(sampleJsonObject, null, 4); 
   $('#dump').html(dump)
</script>

var dump=JSON.stringify(sampleJsonObject,null,4);
$('#dump').html(dump)

很多人都在这个线程中编写代码,对各种Gotcha都有很多评论。我喜欢这个解决方案,因为它看起来很完整,是一个没有依赖关系的单一文件

它是“开箱即用”的,有节点和浏览器两个版本(可能只是不同的包装器,但我没有挖掘来确认)


该库还支持漂亮的打印XML、SQL和CSS,但我还没有尝试过这些功能。

对于那些想以一种很棒的方式查看对象的人

创建一个带有可配置视图选项的表,以便打印到文档的某个位置。最好在
控制台中查看

var tbl = prettyPrint( myObject, { /* options such as maxDepth, etc. */ });
document.body.appendChild(tbl);

将元素打印为字符串的简单方法:

var s = "";
var len = array.length;
var lenMinus1 = len - 1
for (var i = 0; i < len; i++) {
   s += array[i];
   if(i < lenMinus1)  {
      s += ", ";
   }
}
alert(s);
var s=”“;
var len=array.length;
变量lenminss1=len-1
对于(变量i=0;i
我的库既有Ruby也有Ruby。它在(许可的)MIT许可下免费提供。您可以在以下位置查看在线演示/转换器:

一些功能(全部可选):

  • 以特定宽度换行;如果对象或数组可以放在一行上,则将其保留在一行上
  • 对齐对象中所有关键点的冒号
  • 按字母顺序对对象的键进行排序
  • 将浮点数格式化为特定的小数位数