Dmitry Klochkov
Dmitry Klochkov

Reputation: 2635

How to convert an object to its literal string?

I have a string containing an object literal:

var literalStr = "{
     a: 1, 
     b: function(){return 'b'}
 }";

I can create an object from the string:

var obj = eval("(" + literalStr + ")");

Is there a simple way to get the literal string back from the object?

I am looking for something like JSON.stringify() but so it create the original literal with functions and properties names without quotes.

Upvotes: 1

Views: 115

Answers (2)

Benoit Blanchon
Benoit Blanchon

Reputation: 14521

function stringify(source) {
    if (typeof (source) == "object") {
        var str = "{";
        for (var key in source) {
            var value = source[key];
            str += key + ":" + stringify(value) + ",";
        }
        return str.substring(0,str.length-1) + "}";
    }
    return source.toString();
}

then

console.log(stringify(obj));
// writes "{a:1,b:function (){return 'b'}}"

Demo in jsFiddle

Upvotes: 0

Bergi
Bergi

Reputation: 664444

You are looking for the non-standard toSource method(s). Notice that a cross-browser version is impossible, because some js engines provide no possibility to get the source string from a function.

Upvotes: 1

Related Questions