Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Private fields in Javascript don't show up in JSON.stringify

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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())

about 4 years ago · Juan Pablo Isaza Report

0

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());

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!