[英]How to convert an ES6 class to json and parse json to that class object in javascript
[英]How to convert class into json in javascript?
我需要从 class
我试过这个,但我不需要在构造函数中初始化 class 。 如果我能在 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;
});
}
谢谢!
Any object in javascript can be converted to JSON using the JSON.stringify
function. 你可以在这里阅读更多关于它的信息。
JSON.stringify(yourClass);
所以在你的情况下是:
let exampleClass = new ClassExamle()
console.log(JSON.stringify(exampleClass));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.