[英]How to convert class into json in javascript?
I need to get JSON object from class我需要从 class
I tried this, but I don't need initialization of class in constructor.我试过这个,但我不需要在构造函数中初始化 class 。 And it would be perfect if I would get types of attributes in JSON object.如果我能在 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!谢谢!
Any object in javascript can be converted to JSON using the JSON.stringify
function. 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.