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

例子:

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

输出:

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


当前回答

我用for in和template literal来在字符串中有两个键-值对,这对我有用。

让obj = { 名称:“约翰”, 年龄:22岁 isDev:没错, }; let toStr = ""; For (let key in obj) { if (obj.hasOwnProperty(key)) { toStr += ' ${key} ${obj[key]} ' + ", "; } } console.log (toStr); console.log (typeof toStr);

其他回答

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

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

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

如果只是想查看用于调试的对象,可以使用

var o = {a:1, b:2} 
console.dir(o)

如果您正在使用Dojo javascript框架,那么已经有一个内置函数来完成此工作:Dojo . tojson(),它将像这样使用。

var obj = {
  name: 'myObj'
};
dojo.toJson(obj);

它将返回一个字符串。如果要将对象转换为json数据,则添加第二个参数true。

dojo.toJson(obj, true);

http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson

这里没有一个解决方案对我有效。JSON。stringify似乎是很多人所说的,但它削减了函数,并且在我测试时尝试的一些对象和数组似乎很坏。

我做了自己的解决方案,至少在Chrome中工作。把它贴在这里,这样任何在谷歌上看到的人都能找到它。

//Make an object a string that evaluates to an equivalent object
//  Note that eval() seems tricky and sometimes you have to do
//  something like eval("a = " + yourString), then use the value
//  of a.
//
//  Also this leaves extra commas after everything, but JavaScript
//  ignores them.
function convertToText(obj) {
    //create an array that will later be joined into a string.
    var string = [];

    //is object
    //    Both arrays and objects seem to return "object"
    //    when typeof(obj) is applied to them. So instead
    //    I am checking to see if they have the property
    //    join, which normal objects don't have but
    //    arrays do.
    if (typeof(obj) == "object" && (obj.join == undefined)) {
        string.push("{");
        for (prop in obj) {
            string.push(prop, ": ", convertToText(obj[prop]), ",");
        };
        string.push("}");

    //is array
    } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
        string.push("[")
        for(prop in obj) {
            string.push(convertToText(obj[prop]), ",");
        }
        string.push("]")

    //is function
    } else if (typeof(obj) == "function") {
        string.push(obj.toString())

    //all other values can be done with JSON.stringify
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join("")
}

编辑:我知道这段代码可以改进,但只是从来没有做过。用户andrey在评论中提出了一个改进:

这里有一点变化的代码,它可以处理'null'和'undefined',也没有添加过多的逗号。

使用它在你自己的风险,因为我没有验证它在所有。请随意提出任何额外的改进意见。

在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