4

I'm trying to find a way to exchange data using JSON and ES6 classes.

Suppose that I have the following ES6 class definition:

export default class Point {
    constructor(data = {}) {
        Object.assign(this, data);
    }
    get x() { return this._x; }
    set x(val) { this._x = val; }
    get y() { return this._y; }
    set y(val) { this._y = val; }
}

And the following object instance:

let jsonIn = JSON.parse("{"x": "34", "y": "28"}");
let myPoint = new Point(jsonIn);

Upon inspection, myPoint will correctly have two "internal" attributes named _x and _y set to 34 and 28, respectively. So object hydration from JSON to an ES6 class instance is possible.

However, if I now try to serialize this instance back to JSON:

let myJson = JSON.stringify(myPoint);

I get the following:

> "{"_x":"34","_y":"28"}"

Is it possible or legal to name the serialized JSON keys as the object's public property getter names instead? Something like this?

> "{"x": "34", "y": "28"}"

Thanks!

Jesús Zazueta
  • 1,160
  • 1
  • 17
  • 32
  • possible duplicate of [Convert ES6 Class to JSON](http://stackoverflow.com/q/33382939/1048572) – Bergi Nov 09 '15 at 02:21

1 Answers1

5

This hasn't changed with ES2015. You still simply define a custom toJSON method:

toJSON() {
  return {x: this.x, y: this.y};
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Ah, of course. I had no idea there was a hook into the serialization mechanism. That should be enough to solve my problem. Much appreciated! :D. – Jesús Zazueta Nov 09 '15 at 01:20