Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert class into json in javascript?

I need to get JSON object from class

I tried this, but I don’t need initialization of class in constructor. And it would be perfect if I would get types of attributes in JSON object.

class ClassExamle {
    constructor(n) {
      this.name = n;
      this.mapOfClassExamle = new Map();
    }
}

function intoJSON(instance) {
    return JSON.stringify(instance, (key, value) => {
      if(value instanceof ClassExamle) {
        //only return serialisible fields
        const  { name, mapOfClassExamle } = value;
        //return plain object 
        return { name, mapOfClassExamle };
      }
      
      //convert map to plain object
      if(value instanceof Map) {
        return Object.fromEntries(value);
      }
  
      return value;
    });
}

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Any object in javascript can be converted to JSON using the JSON.stringify function. You can read more about it here.

JSON.stringify(yourClass);

So in your case it’s:

let exampleClass = new ClassExamle()
console.log(JSON.stringify(exampleClass));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading