Converting an object to a string

2018-12-31 17:03发布

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 :(

30条回答
皆成旧梦
2楼-- · 2018-12-31 17:25

If all you want is to simply get a string output, then this should work: String(object)

查看更多
高级女魔头
3楼-- · 2018-12-31 17:26

None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.

I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.

//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("")
}

EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:

Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.

Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.

查看更多
浪荡孟婆
4楼-- · 2018-12-31 17:26

If you just want to see the object for debugging, you can use

var o = {a:1, b:2} 
console.dir(o)
查看更多
栀子花@的思念
5楼-- · 2018-12-31 17:27

Take a look at the jQuery-JSON plugin

At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.

查看更多
明月照影归
6楼-- · 2018-12-31 17:28
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);
查看更多
不再属于我。
7楼-- · 2018-12-31 17:32

EDIT Do not use this answer as it does not work in Internet Explorer. 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());
查看更多
登录 后发表回答