Converting an object to a string

后端 未结 30 1829
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

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

Output:

相关标签:
30条回答
  • 2020-11-22 04: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);
    
    0 讨论(0)
  • 2020-11-22 04:15

    There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:

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

    I would prefer this as JSON.stringify() has certain limitations (e.g. with circular structures).

    0 讨论(0)
  • 2020-11-22 04:16

    Keeping it simple with console, you can just use a comma instead of a +. The + will try to convert the object into a string, whereas the comma will display it separately in the console.

    Example:

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

    Output:

    Object { a=1, b=2}           // useful
    Item: [object Object]        // not useful
    Item:  Object {a: 1, b: 2}   // Best of both worlds! :)
    

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

    0 讨论(0)
  • 2020-11-22 04:16

    stringify-object is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-object

    npm install stringify-object
    

    then:

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

    Obviously it's interesting only if you have circular object that would fail with JSON.stringify();

    0 讨论(0)
  • 2020-11-22 04:17

    If you are using the Dojo javascript framework then there is already a build in function to do this: dojo.toJson() which would be used like so.

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

    which will return a string. If you want to convert the object to json data then add a second parameter of true.

    dojo.toJson(obj, true);
    

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

    0 讨论(0)
  • 2020-11-22 04:18

    EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.

    toSource() is the function you are looking for which will write it out as JSON.

    var object = {};
    object.first = "test";
    object.second = "test2";
    alert(object.toSource());
    
    0 讨论(0)
提交回复
热议问题