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

例子:

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

输出:

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


当前回答

对于非嵌套对象:

Object.entries(o).map(x=>x.join(":")).join("\r\n")

其他回答

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

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

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

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

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

  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

看看jQuery-JSON插件

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

/*
    This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
    Params:
        obj - your object
        inc_ident - can be " " or "\t".
        show_types - show types of object or not
        ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
    var res = "";
    if (!ident)
        ident = "";
    if (typeof(obj) == "string") {
        res += "\"" + obj + "\" ";
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
    } else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
        res += obj;
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
    } else if (obj instanceof Array) {
        res += "[ ";
        res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
        res += "\r\n";
        var new_ident = ident + inc_ident;
        var arr = [];
        for(var key in obj) {
            arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
        } 
        res += arr.join(",\r\n") + "\r\n";
        res += ident + "]";
    } else {
        var new_ident = ident + inc_ident;      
        res += "{ ";
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
        res += "\r\n";
        var arr = [];
        for(var key in obj) {
            arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
        }
        res += arr.join(",\r\n") + "\r\n";
        res += ident + "}\r\n";
    } 
    return res;
};

示例:

var obj = {
    str : "hello",
    arr : ["1", "2", "3", 4],
b : true,
    vobj : {
        str : "hello2"
    }
}

var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();

f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();

your_object1.txt:

{ 
    "str" : "hello" ,
    "arr" : [ 
        "1" ,
        "2" ,
        "3" ,
        4
    ],
    "b" : true,
    "vobj" : { 
        "str" : "hello2" 
    }

}

your_object2.txt:

{ /* typeobj: object*/
    "str" : "hello" /* typeobj: string*/,
    "arr" : [ /* typeobj: object*/
        "1" /* typeobj: string*/,
        "2" /* typeobj: string*/,
        "3" /* typeobj: string*/,
        4/* typeobj: number*/
    ],
    "b" : true/* typeobj: boolean*/,
    "vobj" : { /* typeobj: object*/
        "str" : "hello2" /* typeobj: string*/
    }

}

我正在寻找这个,并写了一个深度递归缩进:

function objToString(obj, ndeep) {
  if(obj == null){ return String(obj); }
  switch(typeof obj){
    case "string": return '"'+obj+'"';
    case "function": return obj.name || obj.toString();
    case "object":
      var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
      return '{['[+isArray] + Object.keys(obj).map(function(key){
           return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
         }).join(',') + '\n' + indent + '}]'[+isArray];
    default: return obj.toString();
  }
}

使用方法:objToString({a: 1, b: {c: "test"}})