Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  11] [ 7]  / answers: 1 / hits: 55595  / 8 Years ago, sun, october 23, 2016, 12:00:00
class MyClass {
constructor() {
this.foo = 3
}
}

var myClass = new MyClass()


I'd like to serialize myClass object to json.



One easy way I can think of is, since every member is actually javascript object (array, etc..) I guess I can maintain a variable to hold the member variables.



this.prop.foo = this.foo and so on.



I expected to find a toJSON/fromJSON library for class objects since I used them with other languages such as swift/java, but couldn't find one for javascript.



Maybe class construct is too new, or what I'm asking can be somehow easily achieved without a library.


More From » json

 Answers
2

As with any other object you want to stringify in JS, you can use JSON.stringify:



JSON.stringify(yourObject);







class MyClass {
constructor() {
this.foo = 3
}
}

var myClass = new MyClass()

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





Also worth noting is that you can customize how stringify serializes your object by giving it a toJSON method. The value used to represent your object in the resulting JSON string will be the result of calling the toJSON method on that object.


[#60307] Thursday, October 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikokorbinm

Total Points: 744
Total Questions: 126
Total Answers: 104

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;