![](/img/trans.png)
[英]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.