如何以字符串格式显示 JavaScript 对象的内容,就像我们alert
使用变量时一样?
我想显示对象的格式相同。
如何以字符串格式显示 JavaScript 对象的内容,就像我们alert
使用变量时一样?
我想显示对象的格式相同。
使用本机JSON.stringify
方法。适用于嵌套对象,所有主流浏览器都支持此方法。
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
链接到Mozilla API 参考和其他示例。
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
如果遇到此 Javascript 错误,请使用自定义JSON.stringify 替换器
"Uncaught TypeError: Converting circular structure to JSON"
如果要打印对象以进行调试,请使用以下代码:
var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)
将显示:
注意:您必须只记录对象。例如,这不起作用:
console.log('My object : ' + obj)
注意 ':您也可以在log
方法中使用逗号,然后输出的第一行将是字符串,之后将呈现对象:
console.log('My object: ', obj);
var output = '';
for (var property in object) {
output += property + ': ' + object[property]+'; ';
}
alert(output);
console.dir(object)
:
显示指定 JavaScript 对象的属性的交互式列表。此列表允许您使用显示三角形来检查子对象的内容。
请注意,该console.dir()
功能是非标准的。查看MDN 网络文档
console.log(JSON.stringify(obj))
这将打印对象的字符串化版本。因此,您将获得对象的内容,而不是[object]
作为输出。
好吧,Firefox(感谢@Bojangles 提供详细信息)具有Object.toSource()
将对象打印为 JSON 和function(){}
.
我猜这对于大多数调试目的来说已经足够了。
如果你想使用 alert 来打印你的对象,你可以这样做:
alert("myObject is " + myObject.toSource());
它应该以字符串格式打印每个属性及其对应的值。
如果您想以表格格式查看数据,您可以使用
console.table(obj);
如果单击表格列,可以对表格进行排序。
您还可以选择要显示的列:
console.table(obj, ['firstName', 'lastName']);
您可以在此处找到有关 console.table 的更多信息
功能:
var print = function(o){
var str='';
for(var p in o){
if(typeof o[p] == 'string'){
str+= p + ': ' + o[p]+'; </br>';
}else{
str+= p + ': { </br>' + print(o[p]) + '}';
}
}
return str;
}
用法:
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
例子:
在 NodeJS 中,您可以使用util.inspect(obj)
. 一定要说明深度,否则你只会得到物体的浅印。
只需使用
JSON.stringify(obj)
例子
var args_string = JSON.stringify(obj);
console.log(args_string);
或者
alert(args_string);
此外,javascript 函数中的注释被视为对象。
作为额外说明:
实际上,您可以像这样分配新属性并访问它 console.log 或在警报中显示它
foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
注意:在这些示例中,yourObj 定义了您要检查的对象。
这是显示对象内容的事实上的方式
console.log(yourObj)
console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));
Object.keys(yourObj).forEach(e => console.log(`key=${e} value=${yourObj[e]}`));
这将产生整洁的输出:
上一个答案中提到的解决方案:
console.log(yourObj)
显示太多参数,不是显示所需数据的最用户友好的方式。这就是为什么我建议分别记录键和值的原因。
console.table(yourObj)
在较早的评论中有人提出了这个建议,但它对我没有用。如果它确实适用于其他浏览器或其他东西上的其他人,那么恭喜!我还是把代码放在这里供参考!将这样的输出到控制台:
使用Node.js打印带有颜色的完整对象作为奖励:
console.dir(object, {depth: null, colors: true})
颜色当然是可选的,'depth: null' 将打印完整的对象。
浏览器似乎不支持这些选项。
参考:
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://nodejs.org/api/console.html#console_console_dir_obj_options
用这个:
console.log('print object: ' + JSON.stringify(session));
正如之前所说,我发现的最好和最简单的方法是
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
(这已添加到我在GitHub的库中)
在这里重新发明轮子!这些解决方案都不适用于我的情况。因此,我迅速修改了wilsonpage的答案。这不是用于打印到屏幕(通过控制台或文本字段或其他)。它在这些情况下确实可以正常工作,并且可以按照 OP 的要求正常工作,对于alert
. 这里的许多答案都没有alert
按照 OP 的要求使用。无论如何,它是为数据传输而格式化的。此版本似乎返回与toSource()
. 我没有针对 进行测试JSON.stringify
,但我认为这是同一件事。这个版本更像是一个 poly-fil,因此您可以在任何环境中使用它。此函数的结果是有效的 Javascript 对象声明。
我不会怀疑这样的东西是否已经在某个地方出现了,但是制作它比花一些时间搜索过去的答案要短。因为当我开始搜索这个问题时,这个问题是我在谷歌上的热门话题;我想把它放在这里可能会帮助其他人。
无论如何,这个函数的结果将是你的对象的字符串表示,即使你的对象有嵌入的对象和数组,即使这些对象或数组有更多的嵌入对象和数组。(听说你喜欢喝酒?所以,我用冷却器拉了你的车。然后,我用冷却器拉了你的冷却器。所以,你的冷却器可以喝,而你很酷。)
数组与[]
而不是存储,{}
因此没有键/值对,只有值。像常规数组一样。因此,它们像数组一样被创建。
此外,所有字符串(包括键名)都被引用,除非这些字符串具有特殊字符(如空格或斜杠),否则这不是必需的。但是,我不想检测这个只是为了删除一些否则仍然可以正常工作的引号。
然后可以使用此生成的字符串eval
或将其转储到 var thru 字符串操作中。因此,从文本重新创建您的对象。
function ObjToSource(o){
if (!o) return 'null';
var k="",na=typeof(o.length)=="undefined"?1:0,str="";
for(var p in o){
if (na) k = "'"+p+ "':";
if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
else str += k + o[p] + ",";
}
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
如果我把这一切搞砸了,请告诉我,在我的测试中工作正常。此外,我能想到的检测类型的唯一方法array
是检查length
. 因为 Javascript 确实将数组存储为对象,所以我实际上无法检查类型array
(没有这种类型!)。如果其他人知道更好的方法,我很想听听。因为,如果你的对象也有一个名为的属性,length
那么这个函数会错误地将它视为一个数组。
编辑:添加了对空值对象的检查。谢谢布洛克亚当斯
编辑:下面是能够打印无限递归对象的固定函数。这与toSource
从 FF 打印的内容不同,因为toSource
将打印一次无限递归,而此函数将立即终止它。这个函数比上面的运行得慢,所以我在这里添加它而不是编辑上面的函数,因为只有当你计划在某个地方传递链接回它们自己的对象时才需要它。
const ObjToSource=(o)=> {
if (!o) return null;
let str="",na=0,k,p;
if (typeof(o) == "object") {
if (!ObjToSource.check) ObjToSource.check = new Array();
for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
ObjToSource.check.push(o);
}
k="",na=typeof(o.length)=="undefined"?1:0;
for(p in o){
if (na) k = "'"+p+"':";
if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
else str += k+o[p]+",";
}
if (typeof(o) == "object") ObjToSource.check.pop();
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
测试:
var test1 = new Object();
test1.foo = 1;
test1.bar = 2;
var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;
console.log(ObjToSource(testobject));
console.log(testobject.toSource());
结果:
{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})
注意:尝试打印document.body
是一个糟糕的例子。一方面,FF 在使用时只打印一个空对象字符串toSource
。而当使用上面的函数时,FF 在SecurityError: The operation is insecure.
. Chrome 会在Uncaught RangeError: Maximum call stack size exceeded
. 显然,document.body
并不是要转换为字符串。因为它要么太大,要么违反安全策略来访问某些属性。除非,我在这里搞砸了,请告诉我!
这是一种方法:
console.log("%o", obj);
如果您想打印其全长的对象,可以使用
console.log(require('util').inspect(obj, {showHidden: false, depth: null})
如果要通过将对象转换为字符串来打印对象,则
console.log(JSON.stringify(obj));
我需要一种递归打印对象的方法,该对象提供了 pagewil 的答案(谢谢!)。我对其进行了一些更新,以包含一种打印到某个级别的方法,并添加间距,以便根据我们所处的当前级别正确缩进,使其更具可读性。
// Recursive print of object
var print = function( o, maxLevel, level ) {
if ( typeof level == "undefined" ) {
level = 0;
}
if ( typeof level == "undefined" ) {
maxLevel = 0;
}
var str = '';
// Remove this if you don't want the pre tag, but make sure to remove
// the close pre tag on the bottom as well
if ( level == 0 ) {
str = '<pre>';
}
var levelStr = '';
for ( var x = 0; x < level; x++ ) {
levelStr += ' ';
}
if ( maxLevel != 0 && level >= maxLevel ) {
str += levelStr + '...</br>';
return str;
}
for ( var p in o ) {
if ( typeof o[p] == 'string' ) {
str += levelStr +
p + ': ' + o[p] + ' </br>';
} else {
str += levelStr +
p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
}
}
// Remove this if you don't want the pre tag, but make sure to remove
// the open pre tag on the top as well
if ( level == 0 ) {
str += '</pre>';
}
return str;
};
用法:
var pagewilsObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
// Recursive of whole object
$('body').append( print(pagewilsObject) );
// Recursive of myObject up to 1 level, will only show name
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) );
您还可以使用 ES6 模板字面量概念以字符串格式显示 JavaScript 对象的内容。
alert(`${JSON.stringify(obj)}`);
const obj = {
"name" : "John Doe",
"habbits": "Nothing",
};
alert(`${JSON.stringify(obj)}`);
我总是用console.log("object will be: ", obj, obj1)
. 这样我就不需要使用 JSON 进行字符串化的解决方法。对象的所有属性都将很好地扩展。
在控制台中显示对象的另一种方法是使用JSON.stringify
. 查看以下示例:
var gandalf = {
"real name": "Gandalf",
"age (est)": 11000,
"race": "Maia",
"haveRetirementPlan": true,
"aliases": [
"Greyhame",
"Stormcrow",
"Mithrandir",
"Gandalf the Grey",
"Gandalf the White"
]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
Javascript 函数
<script type="text/javascript">
function print_r(theObj){
if(theObj.constructor == Array || theObj.constructor == Object){
document.write("<ul>")
for(var p in theObj){
if(theObj[p].constructor == Array || theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
document.write("<ul>")
print_r(theObj[p]);
document.write("</ul>")
} else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
}
}
document.write("</ul>")
}
}
</script>
打印对象
<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script>
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
object
你的对象在哪里
或者您可以在 chrome 开发工具的“控制台”选项卡中使用它:
console.log(object);
假设对象obj = {0:'John', 1:'Foo', 2:'Bar'}
打印对象的内容
for (var i in obj){
console.log(obj[i], i);
}
控制台输出(Chrome DevTools):
John 0
Foo 1
Bar 2
希望有帮助!
如果您正在寻找 Node.js 的内联...
console.log("%o", object);
我总是在我的项目中使用一个小助手功能,通过控制台进行简单、快速的调试。灵感来自 Laravel。
/**
* @param variable mixed The var to log to the console
* @param varName string Optional, will appear as a label before the var
*/
function dd(variable, varName) {
var varNameOutput;
varName = varName || '';
varNameOutput = varName ? varName + ':' : '';
console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}
用法
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
console.log() 在调试对象方面做得很好,但是如果您希望将对象打印到页面内容,这是我想出的模仿 PHP 的 print_r() 功能的最简单方法。很多其他答案都想重新发明轮子,但是在 JavaScript 的 JSON.stringify() 和 HTML 的 <pre> 标记之间,你得到的正是你想要的。
var obj = { name: 'The Name', contact: { email: 'thename@gmail.com', tel: '123456789' }};
$('body').append('<pre>'+JSON.stringify(obj, null, 4)+'</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我使用了 pagewil 的打印方法,效果非常好。
这是我稍微扩展的版本,带有(草率的)缩进和不同的 prop/ob 分隔符:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};
pagewils 代码的另一种修改......他不打印字符串以外的任何内容,并将数字和布尔字段留空,我修复了由 megaboss 创建的函数内部的第二种 typeof 的错字。
var print = function( o, maxLevel, level )
{
if ( typeof level == "undefined" )
{
level = 0;
}
if ( typeof maxlevel == "undefined" )
{
maxLevel = 0;
}
var str = '';
// Remove this if you don't want the pre tag, but make sure to remove
// the close pre tag on the bottom as well
if ( level == 0 )
{
str = '<pre>'; // can also be <pre>
}
var levelStr = '<br>';
for ( var x = 0; x < level; x++ )
{
levelStr += ' '; // all those spaces only work with <pre>
}
if ( maxLevel != 0 && level >= maxLevel )
{
str += levelStr + '...<br>';
return str;
}
for ( var p in o )
{
switch(typeof o[p])
{
case 'string':
case 'number': // .tostring() gets automatically applied
case 'boolean': // ditto
str += levelStr + p + ': ' + o[p] + ' <br>';
break;
case 'object': // this is where we become recursive
default:
str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
break;
}
}
// Remove this if you don't want the pre tag, but make sure to remove
// the open pre tag on the top as well
if ( level == 0 )
{
str += '</pre>'; // also can be </pre>
}
return str;
};
这里的功能。
function printObj(obj) {
console.log((function traverse(tab, obj) {
let str = "";
if(typeof obj !== 'object') {
return obj + ',';
}
if(Array.isArray(obj)) {
return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
}
str = str + '{\n';
for(var p in obj) {
str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
}
str = str.slice(0,-2) + str.slice(-1);
str = str + tab + '},';
return str;
}('',obj).slice(0,-1)))};
它可以使用具有可读性的制表符缩进显示对象。
如果您正在寻找可以返回任何 javascript 对象的美化字符串的东西,请查看https://github.com/fresheneesz/beautinator。一个例子:
var result = beautinator({ "font-size": "26px","font-family": "'Open Sans', sans-serif",color: "white", overflow: "hidden",padding: "4px 4px 4px 8px",Text: { display: "block", width: "100%","text-align": "center", "padding-left": "2px","word-break": "break-word"}})
console.log(result)
结果是:
{ "font-size": "26px",
"font-family": "'Open Sans', sans-serif",
color: "white", overflow: "hidden",
padding: "4px 4px 4px 8px",
Text: { display: "block", width: "100%",
"text-align": "center", "padding-left": "2px",
"word-break": "break-word"
}
}
如果您的对象中有函数,它甚至可以工作。
要从包含重复引用(在许多地方对同一对象的引用)包括循环引用的对象制作没有冗余信息的字符串JSON.stringify
,请使用替换器(在片段中显示),如下所示
let s = JSON.stringify(obj, refReplacer(), 4);
function refReplacer() {
let m = new Map(), v= new Map(), init = null;
return function(field, value) {
let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field);
let isComplex= value===Object(value)
if (isComplex) m.set(value, p);
let pp = v.get(value)||'';
let path = p.replace(/undefined\.\.?/,'');
let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
!init ? (init=value) : (val===init ? val="#REF:$" : 0);
if(!pp && isComplex) v.set(value, path);
return val;
}
}
// ---------------
// TEST
// ---------------
// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2: a }, b, a }; // duplicate reference
a.a3 = [1,2,b]; // circular reference
b.b3 = a; // circular reference
let s = JSON.stringify(obj, refReplacer(), 4);
console.log(s);
alert(s);
此解决方案基于此 (此处有更多信息)为每个对象值创建类似JSONPath的路径,如果相同的对象出现两次(或更多),它使用此路径的引用来引用该对象,例如#REF:$.bar.arr[3].foo
(其中$
表示主对象)而不是“渲染”整个对象(冗余较少)
奖金:反转
function parseRefJSON(json) {
let objToPath = new Map();
let pathToObj = new Map();
let o = JSON.parse(json);
let traverse = (parent, field) => {
let obj = parent;
let path = '#REF:$';
if (field !== undefined) {
obj = parent[field];
path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
}
objToPath.set(obj, path);
pathToObj.set(path, obj);
let ref = pathToObj.get(obj);
if (ref) parent[field] = ref;
for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
}
traverse(o);
return o;
}
// ------------
// TEST
// ------------
let s = `{
"o1": {
"o2": {
"a1": 1,
"a2": 2,
"a3": [
1,
2,
{
"b1": 3,
"b2": "4",
"b3": "#REF:$.o1.o2"
}
]
}
},
"b": "#REF:$.o1.o2.a3[2]",
"a": "#REF:$.o1.o2"
}`;
console.log('Open Chrome console to see nested fields');
let obj = parseRefJSON(s);
console.log(obj);
显示对象内容的一种简单方法是使用 console.log,如下所示
console.log("Object contents are ", obj);
请注意,我没有使用“+”来连接对象。如果我使用“+”,那么我将只获得对象的字符串表示形式,例如 [Object object]。
在 ES2015 中,使用对象文字的简写属性声明语法,您可以记录对象,同时还可以简洁地保留变量名称:
console.log("bwib:", bwib, "bwab:", bwab, "bwob": bwob) // old way A
console.log({bwib: bwib, bwab: bwab, bwob: bwob}) // old way B
console.log({bwib, bwab, bwob}) // ES2015+ way
它在浏览器中不起作用,您可能只需要它以防您想要为您的对象获取有效的 JS 表示而不是 JSON。它只是运行节点内联评估
var execSync = require('child_process').execSync
const objectToSource = (obj) =>
execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })
console.log(objectToSource({ a: 1 }))
你可以使用我的功能。
使用数组或字符串或它警告内容的对象调用此函数。
功能
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
用法
var data = [1, 2, 3, 4];
print_r(data);
似乎一个简单for...in
的方法无法解决问题,尤其是当我们想要处理自定义、主机、本机或 CSSOM 对象之外的问题时。此外,我们在这里谈论调试,谁知道我们何时何地需要它!
我的小图书馆可以处理这样的对象:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
并以丰富多彩的方式呈现它们,例如:
但看到那里:
有一些预防措施甚至document.body
被解析!