Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize JavaScript object into JSON string

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?

like image 313
Kalamarico Avatar asked Nov 17 '11 09:11

Kalamarico


People also ask

How do you turn an object into a string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How do you serialize a string in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .

Which method is used to convert JS object to JSON format?

With the help of the JSON. stringify() method, you can easily convert a JavaScript object into a string that will have a valid JSON format. It is typically used for generating a ready-made string that can be delivered to a server. This write-up will explain JSON.


1 Answers

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 }}; 
like image 199
Jakub Konecki Avatar answered Oct 18 '22 20:10

Jakub Konecki