Jesús Zazueta
Jesús Zazueta

Reputation: 1192

Exchanging data with ES6 classes and JSON

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!

Upvotes: 4

Views: 3368

Answers (1)

Felix Kling
Felix Kling

Reputation: 816482

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

toJSON() {
  return {x: this.x, y: this.y};
}

Upvotes: 5

Related Questions