Skip to content

How to get a property with get/set to serialize with JSON.stringify()

I have the following scenario:

var msp = function () { 
  this.val = 0.00;
  this.disc = 0;

Object.defineProperty(msp.prototype, "x", {
                        get: function () {return this.val - this.disc;},
                        toJSON: function () {return this.val - this.disc;},
                        enumerable: true,
                        configurable: true
var mp = new msp();
JSON.stringify(mp); // only returns {"val":0,"disc":0}

I was hoping that I can somehow set a toJSON method on the property “x” in the defineProperty call, but that didn’t work.

Any help would be appreciated.



This is what worked for me:

var obj = function() {
    this.val = 10.0;
    this.disc = 1.5;
    Object.defineProperties(this, {
        test: {
            get: function() { return this.val - this.disc; },
            enumerable: true

var o = new obj;
JSON.stringify(o);   // output: {"val":10,"disc":1.5,"test":8.5}

Note test is not a prototype definition and enumerable has to be set to true.

I tested the above working version in IE9, FF 11 and Chrome 18 – all three gave expected results.

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