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

例子:

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

输出:

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


当前回答

如果你想在内联表达式类型的情况下用最简单的方法将变量转换为字符串,“+variablename是我打过的最好的球。

如果'variablename'是一个对象,你使用空字符串连接操作,它将给出烦人的[object object],在这种情况下,你可能想要Gary C。JSON获得了极大的好评。stringify问题的答案,你可以在Mozilla的开发者网络的答案在顶部的链接中阅读。

其他回答

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

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"}})

/*
    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*/
    }

}

看看jQuery-JSON插件

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

在检查最后一项时,使用reduce来更改(key,value)元组之间的分隔符sep的修改方法:

/**
     * Object to string
     * @param {*} obj 
     * @param {*} k_sep keys separator
     * @param {*} v_sep values separator
     * @returns 
     */
    var objectToString: function (obj, k_sep = '=', v_sep = ',') {
      const entries = Object.entries(obj);
      return entries.reduce((str, [p, val], counter) => {
        if (counter < entries.length - 1) {
          return `${str}${p}${k_sep}${val}${v_sep}`;
        } else {
          return `${str}${p}${k_sep}${val}`;
        }
      }, '');
    }

/** * Object to string * @param {*} obj * @param {*} k_sep keys separator * @param {*} v_sep values separator * @returns */ var objectToString = function(obj, k_sep = '=', v_sep = ',') { const entries = Object.entries(obj); return entries.reduce((str, [p, val], counter) => { if (counter < entries.length - 1) { return `${str}${p}${k_sep}${val}${v_sep}`; } else { return `${str}${p}${k_sep}${val}`; } }, ''); } console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, ':', ",")) console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, '=', ","))

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

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

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