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

例子:

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

输出:

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


当前回答

JSON似乎接受了第二个参数,可以帮助函数- replace,这以最优雅的方式解决了转换问题:

JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return String(val);
    }
    return val;
  });

其他回答

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

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

在检查最后一项时,使用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());

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]

再加上——

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