Home > Back-end >  Private fields in Javascript don't show up in JSON.stringify
Private fields in Javascript don't show up in JSON.stringify

Time:11-05

So if I write a class as follows

class Rectangle {
   #width;
   #height;
   constructor() {
      this.#width = 3;
      this.#height = 5; 
   }

}

let rect = new Rectangle();

console.log(JSON.stringify(rect)); // returns {}

It will return an empty object, totally ignoring all of my private members. Adding a toJSON method works but that becomes very cumbersome. Is there any built-in way that I can easily get my private fields to show up in JSON.stringify? Or do I just have to write in every single member into a toJSON method?

CodePudding user response:

Private properties are only accessible inside the class declaration itself. You'll need to write your own serialization method:

class Rectangle {
  #width;
  #height;
  constructor() {
    this.#width = 3;
    this.#height = 5;
  }

  stringify() {
    return JSON.stringify({['#width']: this.#width,['#height']: this.#height})
  }

}

let rect = new Rectangle();

console.log(rect.stringify())
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

One option to avoid having to write out all the members would be to have a single private data property on the instance, and then serialize / deserialize that property:

class Rectangle {
   #data;
   constructor(data) {
      this.#data = data;
   }
   getWidth = () => this.#data.width;
   toJson = () => JSON.stringify(this.#data);
}
const r = new Rectangle({ width: 1, height: 1 });
console.log(r.getWidth());
const stringified = r.toJson();
console.log(stringified);

const restructured = new Rectangle(JSON.parse(stringified));
console.log(restructured.getWidth());
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related