Home > OS >  How to convert class into json in javascript?
How to convert class into json in javascript?

Time:08-31

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!

CodePudding user response:

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));
  • Related