将一个对象转换为字符串

1202

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

示例:

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

输出:

对象 { a=1, b=2} // 非常良好易读 :)
条目: [object Object] // 不知道里面是什么 :(


7
将字符串转换为什么目的?你是指序列化,以便以后可以从字符串构建对象吗?还是只是为了显示? - Shadow The Spring Wizard
22
作者已经离开多年,但是在我脑海中阅读了多年后,我猜测问题的入口是console.log(obj),它会显示带有属性的对象,而console.log('obj: '+obj)则会产生迷惑。 - Danubian Sailor
2
无法简单地将两个对象相加,如果可以这样做,值类型和引用类型之间就没有区别了。 - Nishant Kumar
13
变量 o 等于 {a:1, b:2}; 打印出字符串 'Item: ' 和对象 o 的 JSON 字符串形式。 - Nishant Kumar
30
如果是针对控制台输出的话,我建议使用 console.log("Item", obj);。不需要过于复杂的代码。 - soktinpk
显示剩余7条评论
42个回答

15
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);

14

实际上,现有答案中缺少一种简单的选择(适用于最近版本的浏览器和Node.js):

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

我更喜欢这样,因为JSON.stringify()有一定的限制(例如,对于循环结构)。


11

如果您只想为调试查看对象,您可以使用

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

10

1.

JSON.stringify(o);

物品:{"a":"1", "b":"2"}

2.

var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);
项目:{a:1,b:2}

3
请考虑在您的答案中添加更多细节,这样会更好。 - Harun Diluka Heshan

10

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

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

9

对于非嵌套的对象:

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

8

与Gecko引擎的.toSource()原始方法相比,JSON方法相当逊色。

有关比较测试,请参见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 encode source code”使用)一样,不能处理循环引用并且不完整。下面的代码显示了它(欺骗)的局限性(已更正以处理没有内容的数组和对象)。

直接链接到代码在//forums.devshed.com/.../tosource-with-arrays-in-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")]

并且

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

并且

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]

7

stringify-object 是由 Yeoman 团队开发的一个不错的 npm 库:https://www.npmjs.com/package/stringify-object

npm install stringify-object

然后:
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);

显然,只有在您拥有会因使用JSON.stringify();而失败的循环对象时,这才是有趣的。

1
为什么有人会使用NPM模块来完成像这样的事情,而这可以通过一行纯JS代码实现?这个答案需要详细说明为什么有人会这样做。 - Zelphir Kaltstahl
通常情况下,库可以帮助处理边缘情况。我使用它来处理循环引用。 - Nicolas Zozol
1
加上关于循环对象的注释后,这就更有意义了,我撤销了我的踩票。 - Zelphir Kaltstahl
@ZelphirKaltstahl,之所以这样做是因为JSON.stringify(obj)生成的结果是{"key":"value"},而我需要的是{key:"value"}。请注意key周围引号的位置。 - Rzassar

5

如果你只关心字符串、对象和数组:

function objectToString (obj) {
        var str = '';
        var i=0;
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if(typeof obj[key] == 'object')
                {
                    if(obj[key] instanceof Array)
                    {
                        str+= key + ' : [ ';
                        for(var j=0;j<obj[key].length;j++)
                        {
                            if(typeof obj[key][j]=='object') {
                                str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
                            }
                            else
                            {
                                str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
                            }
                        }
                        str+= ']' + (i > 0 ? ',' : '')
                    }
                    else
                    {
                        str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
                    }
                }
                else {
                    str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
                }
                i++;
            }
        }
        return str;
    }

5

由于Firefox不会将某些对象转换为屏幕对象;如果您想要与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(',')+'}';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接