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?
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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() .
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.
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 }};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With