Serialize JavaScript object into JSON string

Kalamarico picture Kalamarico · Nov 17, 2011 · Viewed 166.6k times · Source

I have this JavaScript prototype:

Utils.MyClass1 = function(id, member) {
this.id = id;
this.member = member;
}

and I create a new object:

var myobject = new MyClass1("5678999", "text");

If I do:

console.log(JSON.stringify(myobject));

the result is:

{"id":"5678999", "member":"text"}

but I need for the type of the objects to be included in the JSON string, like this:

"MyClass1": { "id":"5678999", "member":"text"} 

Is there a fast way to do this using a framework or something? Or do I need to implement a toJson() method in the class and do it manually?

Answer

Jakub Konecki picture Jakub Konecki · Nov 17, 2011
var myobject = new MyClass1("5678999", "text");
var dto = { MyClass1: myobject };
console.log(JSON.stringify(dto));

EDIT:

JSON.stringify will stringify all 'properties' of your class. If you want to persist only some of them, you can specify them individually like this:

var dto = { MyClass1: {
    property1: myobject.property1,
    property2: myobject.property2
}};