As you said, you wanted to avoid using toJSON in every class (but I also think that using toJSON is the βrightβ thing).
Javascript allows you to do strange things, but at least you can manage it in a closed function area.
I think the regex can be refined, but I just wanted to show this idea, but not really, but should work.
class Foo { constructor(x, y, z) { this._x = x; this._y = y; this._z = z; } get x() { return this._x; } set x(value) { //I acctually do some stuff here this._x = value; } get y() { return this._y; } set y(value) { //I acctually do some stuff here this._y = value; } get z() { return this._z; } set z(value) { //I acctually do some stuff here this._z = value; } } var originalJSON = JSON; var foo = new Foo('x', 'y', 'z'); (function () { var JSON = { stringify: function (obj) { var json = originalJSON.stringify(obj); return json.replace(/"_+(\w+)":/g, '"$1":'); }, parse: function(str) { return originalJSON.parse(str.replace(/"(\w+)":/g, '"_$1":')); } }; console.log('Weird hack'); var r = JSON.stringify(foo); console.log('stringify'); console.log(r); console.log('parse'); console.log(JSON.parse(r)); }).call(); console.log('\nBack to normal'); var r = JSON.stringify(foo); console.log('stringify'); console.log(r); console.log('parse'); console.log(JSON.parse(r));
Output:
Weird hack stringify {"x":"x","y":"y","z":"z"} parse { _x: 'x', _y: 'y', _z: 'z' } Back to normal stringify {"_x":"x","_y":"y","_z":"z"} parse { _x: 'x', _y: 'y', _z: 'z' }
Marcs source share