如何将JavaScript对象转换为字符串?

例子:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

输出:

对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(


当前回答

如果你可以使用lodash,你可以这样做:

> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'

使用lodash map()也可以遍历对象。 这将每个键/值条目映射到它的字符串表示形式:

> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]

join()将数组条目放在一起。

如果你可以使用ES6模板字符串,这也是有效的:

> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'

请注意,这不是递归通过对象:

> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]

就像node的util.inspect()一样:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'

其他回答

var o = {a:1, b:2};

o.toString=function(){
  return 'a='+this.a+', b='+this.b;
};

console.log(o);
console.log('Item: ' + o);

因为Javascript v1.0可以在任何地方工作(甚至是IE) 这是一种本地方法,允许在调试和生产过程中对对象进行定制 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

有用的例子

var Ship=function(n,x,y){
  this.name = n;
  this.x = x;
  this.y = y;
};
Ship.prototype.toString=function(){
  return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
};

alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523

还有,作为奖励

function ISO8601Date(){
  return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
}
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
alert(d);
//IE6   Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29

JSON方法远不如Gecko引擎的. tosource()原语。

有关比较测试,请参阅SO文章响应。

同样,上面的答案指的是http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html,它像JSON一样(另一篇文章http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json通过“ExtJs JSON编码源代码”使用)不能处理循环引用,并且是不完整的。下面的代码显示了它的(欺骗的)限制(修正为处理无内容的数组和对象)。

(直接链接到//forums.devshed.com/中的代码…/ tosource - -数组在ie - 386109)

javascript:
Object.prototype.spoof=function(){
    if (this instanceof String){
      return '(new String("'+this.replace(/"/g, '\\"')+'"))';
    }
    var str=(this instanceof Array)
        ? '['
        : (this instanceof Object)
            ? '{'
            : '(';
    for (var i in this){
      if (this[i] != Object.prototype.spoof) {
        if (this instanceof Array == false) {
          str+=(i.match(/\W/))
              ? '"'+i.replace('"', '\\"')+'":'
              : i+':';
        }
        if (typeof this[i] == 'string'){
          str+='"'+this[i].replace('"', '\\"');
        }
        else if (this[i] instanceof Date){
          str+='new Date("'+this[i].toGMTString()+'")';
        }
        else if (this[i] instanceof Array || this[i] instanceof Object){
          str+=this[i].spoof();
        }
        else {
          str+=this[i];
        }
        str+=', ';
      }
    };
    str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
        (this instanceof Array)
        ? ']'
        : (this instanceof Object)
            ? '}'
            : ')'
    );
    return str;
  };
for(i in objRA=[
    [   'Simple Raw Object source code:',
        '[new Array, new Object, new Boolean, new Number, ' +
            'new String, new RegExp, new Function, new Date]'   ] ,

    [   'Literal Instances source code:',
        '[ [], {}, true, 1, "", /./, function(){}, new Date() ]'    ] ,

    [   'some predefined entities:',
        '[JSON, Math, null, Infinity, NaN, ' +
            'void(0), Function, Array, Object, undefined]'      ]
    ])
alert([
    '\n\n\ntesting:',objRA[i][0],objRA[i][1],
    '\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
    '\ntoSource() spoof:',obj.spoof()
].join('\n'));

显示:

testing:
Simple Raw Object source code:
[new Array, new Object, new Boolean, new Number, new String,
          new RegExp, new Function, new Date]

.toSource()
[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
          /(?:)/, (function anonymous() {}), (new Date(1303248037722))]

toSource() spoof:
[[], {}, {}, {}, (new String("")),
          {}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]

and

testing:
Literal Instances source code:
[ [], {}, true, 1, "", /./, function(){}, new Date() ]

.toSource()
[[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]

toSource() spoof:
[[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]

and

testing:
some predefined entities:
[JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]

.toSource()
[JSON, Math, null, Infinity, NaN, (void 0),
       function Function() {[native code]}, function Array() {[native code]},
              function Object() {[native code]}, (void 0)]

toSource() spoof:
[{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]

请不要使用此答案,因为它只在某些版本的Firefox中有效。没有其他浏览器支持它。使用加里钱伯斯解决方案。

toSource()是您正在寻找的函数,它将以JSON的形式写入。

var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());

看看jQuery-JSON插件

它的核心是使用JSON。但是如果浏览器没有实现它,它就会退回到自己的解析器。

下面是一些简单的解决方案。

它只对字符串显示"",对数字和函数/方法不显示""(如果方法是这样写的):

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod: function() {return "Hi there"}
  };
  
  let readableobj = '{ ';
  
  for(key in obj) {
    readableobj +=
    (typeof obj[key] === "string")? `${key}: "${obj[key]}", ` : `${key}: ${obj[key]}, `;
  }
 
  readableobj += '}';
  
  console.log('obj', readableobj); // obj { name: "Philips TV", price: 42, somemethod: function() {return "Hi there"}, }

这个解决方案使用尾随逗号(自ECMAScript 5起是合法的-请参阅MDN中的参考)。

代码基于'for in'循环的最简单形式:

let obj = {key: "value"};
for(key in obj) {
    return "The property " + key + " with value " + obj[key];
}

注意:它甚至适用于这种方法符号:

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod() {return "Hi there"}
  };

将结果显示为

    obj { name: "Philips TV", price: 42, somemethod: somemethod() {return "Hi there"}, } 

甚至对于箭头函数符号

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod: () => {return "Hi there"}
  };

将结果显示为

    obj { name: "Philips TV", price: 42, somemethod: () => {return "Hi there"}, }

因此,你可以以一种可接受的格式显示一个对象,即使它里面有三种形式的方法符号,就像这样:

  let obj = {
        name: "Philips TV",
        price: 2500,
        method1: function() {return "Hi there"},
        method2() {return "Hi there"},
        method3: () => {return "Hi there"}
  };

有人可能会看到,即使是第二种格式method2() {return "Hi there"},通过复制它的标识符,最终也会显示为一个对键:值

// method2: method2() {return "Hi there"}

最后,true / false、undefined、null的处理方式与数字和函数相同(在最终格式中没有显示“”),因为它们也不是字符串。

重要的是:

JSON.stringify()销毁原始对象,这意味着方法丢失,并且不会显示在由它创建的最终字符串中。

因此,我们可能不应该接受涉及它的使用的解决方案。

console.log('obj', JSON.stringify(obj)); // obj {"name":"Philips TV","price":2500} // which is NOT acceptable