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

例子:

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

输出:

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


当前回答

在console中保持简单,你可以使用逗号而不是+。+将尝试将对象转换为字符串,而逗号将在控制台中单独显示它。

例子:

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

输出:

Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)

参考:https://developer.mozilla.org/en-US/docs/Web/API/Console.log

其他回答

一个选项:

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

另一个选项(正如soktinpk在评论中指出的那样),更适合控制台调试IMO:

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

再加上——

json。stringify(obj)很好, 但它会转换为json string object。 有时候我们需要它的字符串,比如在WCF http post中以body形式发布它并以字符串形式接收。

为此,我们应该重用stringify(),如下所示:

let obj = {id:1, name:'cherry'};
let jsonObj = JSON.stringify(doc); //json object string
let strObj = JSON.stringify(jsonObj); //json object string wrapped with string
var obj={
name:'xyz',
Address:'123, Somestreet'
 }
var convertedString=JSON.stringify(obj) 
 console.log("literal object is",obj ,typeof obj);
 console.log("converted string :",convertedString);
 console.log(" convertedString type:",typeof convertedString);

由于firefox没有将某些对象stringify为屏幕对象;如果你想有相同的结果,如:JSON.stringify(obj):

function objToString (obj) {
    var tabjson=[];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            tabjson.push('"'+p +'"'+ ':' + obj[p]);
        }
    }  tabjson.push()
    return '{'+tabjson.join(',')+'}';
}

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

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

  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