将对象转换为字符串

use*_*174 926 javascript string object tostring

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

例:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Run Code Online (Sandbox Code Playgroud)

输出:

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

Gar*_*ers 1296

我建议使用JSON.stringify,它将对象中的变量集转换为JSON字符串.大多数现代浏览器本机支持此方法,但对于那些不支持此方法的浏览器,您可以包含JS版本:

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);
Run Code Online (Sandbox Code Playgroud)

  • 我得到一个"未捕获的TypeError:将循环结构转换为JSON".即使有循环引用,我仍然希望看到我的对象的字符串表示.我能做什么? (29认同)
  • 如果对象具有函数属性,则不起作用,例如:`foo:function(){...}`. (23认同)
  • 您可以使用 `JSON.stringify(obj, null, 2);` 来获得更漂亮的输出。 (9认同)
  • 作为参考,IE6和7不支持此功能.IE6并不是那么大的交易,因为用户很少,并且有一个活跃的运动来杀死它......但是仍然有相当多的IE7用户(取决于你的用户群). (7认同)
  • 如果从StackOverflow单击,则链接到JSON库不起作用.将其复制并粘贴到地址栏中. (2认同)

Vik*_*ote 103

使用javascript String()函数.

 String(yourobject); //returns [object Object]
Run Code Online (Sandbox Code Playgroud)

要么

JSON.stringify(yourobject)
Run Code Online (Sandbox Code Playgroud)

.

  • var foo = {bar:1}; 串(FOO); - >"[object Object]" (23认同)
  • `JSON.stringify(yourobject)`我的女佣! (5认同)
  • 如果你想将整个对象作为字符串使用JSON.stringify(foo) (2认同)
  • @VikramPote我认为没有办法从“[object Object]”将对象检索到真实状态。 (2认同)

Bre*_*mir 85

当然,要将对象转换为字符串,您必须使用自己的方法,例如:

function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}
Run Code Online (Sandbox Code Playgroud)

实际上,上面只是说明了一般方法; 你可能希望使用http://phpjs.org/functions/var_export:578http://phpjs.org/functions/var_dump:604之类的东西

或者,如果您没有使用方法(作为对象属性的函数),您可以使用新标准(但在旧版浏览器中未实现,但您也可以找到一个实用程序来帮助它们),JSON .stringify().但是,如果对象使用不可序列化为JSON的函数或其他属性,那么这将不起作用.


Luk*_*uke 75

保持简单console,你可以使用逗号代替+.该+会尝试将对象转换为字符串,而逗号将在控制台中单独显示它.

例:

var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o);   // :)
Run Code Online (Sandbox Code Playgroud)

输出:

Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)
Run Code Online (Sandbox Code Playgroud)

参考:https://developer.mozilla.org/en-US/docs/Web/API/Console.log

  • `console.log` 最终调用了称为 `Printer` 的东西,规范指出:“实现如何打印 args 取决于实现” - 这意味着每个浏览器都可以做到这一点(参见 https://console.spec.whatwg .org/#printer)。Firefox 将对象显示为字符串,但颜色很好。Chrome 会将对象显示为一个交互式组,您可以展开该组以查看属性。试一试! (2认同)
  • 非常好的技巧,可能适用于现代Web浏览器,但它并非100%可靠,适用于所有JS实现.例如,在实现JS引擎的Qt QML中,`console.log('Item:',o)的输出;`仍然是`Item:[object Object]`. (2认同)

Gaz*_*ler 33

编辑 不要使用此答案,因为它在Internet Explorer中不起作用.使用Gary Chambers解决方案.

toSource()是您正在寻找的函数,它将其写为JSON.

var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
Run Code Online (Sandbox Code Playgroud)

  • 啊,谢谢你指出这一点.对于那些不知道这一点的人,我会在这里留下我的答案. (11认同)
  • 虽然在Firefox中调试很方便,但是`toSource()`在IE中不起作用. (6认同)
  • `toSource()`不是公认的标准,因此不能保证在所有浏览器中都支持. (4认同)
  • 任何现代浏览器都不支持这一点,这怎么能得到如此多的支持呢?我错过了什么吗?https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toSource (3认同)

nab*_*abn 31

一种选择:

console.log('Item: ' + JSON.stringify(o));

o以字符串形式打印

另一种选择(正如soktinpk在评论中指出的那样),以及更好的控制台调试IMO:

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

o作为对象打印,如果有更多字段,可以向下钻取


Hou*_*ter 20

这里没有一个解决方案适合我.JSON.stringify似乎是很多人所说的,但它削减了函数,对于我在测试时尝试的一些对象和数组看起来很糟糕.

我制作了自己的解决方案,至少在Chrome中有效.在此处发布,以便在Google上查找此内容的任何人都可以找到它.

//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("")
}
Run Code Online (Sandbox Code Playgroud)

编辑:我知道这个代码可以改进,但从来没有做过.用户安德烈提出的改善这里与评论:

这是一个稍微改变的代码,它可以处理'null'和'undefined',也不会添加过多的逗号.

使用它需要您自担风险,因为我根本没有验证过.作为评论,请随意建议任何其他改进.

  • 非常好的代码,但在每个对象/数组的末尾有一个尾随的`,`. (2认同)

Ale*_*ini 19

如果您只是输出到控制台,则可以使用console.log('string:', obj).注意逗号.


Jak*_*rew 16

如果你知道对象只是一个布尔,日期,字符串,数字等... javascript String()函数工作得很好.我最近发现这对于处理来自jquery的$ .each函数的值很有用.

例如,以下内容会将"value"中的所有项目转换为字符串:

$.each(this, function (name, value) {
  alert(String(value));
});
Run Code Online (Sandbox Code Playgroud)

更多细节在这里:

http://www.w3schools.com/jsref/jsref_string.asp

  • 为我工作。我更喜欢这个解决方案,因为我不会为这么简单的任务使用插件。 (2认同)

小智 13

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);
Run Code Online (Sandbox Code Playgroud)


Syl*_*nPV 11

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

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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


小智 10

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

var o = {a:1, b:2} 
console.dir(o)
Run Code Online (Sandbox Code Playgroud)


Eki*_*kim 7

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使用via "ExtJs JSON编码源代码")无法处理循环引用并且不完整.下面的代码显示了它(欺骗)的限制(更正为处理没有内容的数组和对象).

(直接链接到//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'));
Run Code Online (Sandbox Code Playgroud)

显示:

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")]
Run Code Online (Sandbox Code Playgroud)

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")]
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)


小智 7

1.

JSON.stringify(o);
Run Code Online (Sandbox Code Playgroud)

货号:{"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);
Run Code Online (Sandbox Code Playgroud)

货号:{a:1,b:2}

  • 如果您考虑添加有关答案的更多详细信息,会更好。 (3认同)

Chr*_*ron 7

实际上,现有答案中缺少一个简单的选项(对于最新的浏览器和Node.js):

console.log('Item: %o', o);
Run Code Online (Sandbox Code Playgroud)

我希望这样做JSON.stringify()有一定的局限性(例如,采用圆形结构)。


Nic*_*zol 6

stringify-object是 yeoman 团队制作的一个很好的 npm 库:https : //www.npmjs.com/package/stringify-object

npm install stringify-object
Run Code Online (Sandbox Code Playgroud)

然后:

const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
Run Code Online (Sandbox Code Playgroud)

显然只有当你有一个会失败的圆形对象时才有趣 JSON.stringify();


Ale*_*ücs 6

对于非嵌套对象:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
Run Code Online (Sandbox Code Playgroud)


Abd*_*UMI 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(',')+'}';
}
Run Code Online (Sandbox Code Playgroud)


Anu*_*dya 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;
    }
Run Code Online (Sandbox Code Playgroud)


Gle*_*kov 5

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

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


Sha*_*pta 5

也许你正在寻找

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"
Run Code Online (Sandbox Code Playgroud)