Converting an object to a string

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:

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(


I would recommend using JSON.stringify , which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

Sure, to convert an object into a string, you either have to use your own method, such as:

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

Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604

or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.


Use javascript String() function.

 String(yourobject); //returns [object Object]

or

JSON.stringify(yourobject)

.

链接地址: http://www.djcxy.com/p/82466.html

上一篇: 如何在node.js中使用堆栈跟踪console.log发生错误?

下一篇: 将对象转换为字符串