Skip to content
Advertisement

Serializing an ES6 class object as JSON

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement