[英]JSON.stringify not stringifying the whole object
JSON.stringify(this.workout)
不能对整个对象进行字符串化。 workout
是Workout
类中的一个对象,看起来像这样:
export class Workout {
id: string;
name: string;
exercises: Exercise[];
routine: Routine;
}
练习和例程是另一个具有嵌套数组的类。
问题是JSON.stringify(this.workout)
仅返回{"name":"Day 1"}
。 有什么想法可以解决问题吗?
对于要序列化的任何类,可能必须定义toJSON()
方法以确保数据被序列化。 否则,只有常规的可枚举属性将最终出现在输出中。
您可能需要在Exercise
和Routine
以及Workout
。
另请参阅: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
正如您在使用普通JS的本示例中所看到的那样,它可以按预期工作,因此您应查看代码并确保正确初始化了所有对象。
另外,您还可以在这些类中的任何一个中实现自定义toJSON
方法,以定义要序列化它们的方式(请查看class
Routine
的示例):
class Exercises { constructor() { this.items = [1, 2, 3]; } } class Routine { constructor() { this.property = 'DATA'; } toJSON() { return `ROUTINE = ${ this.property }`; } } class Workout { constructor() { this.id = 1; this.name = 'Foo'; this.exercises = new Exercises(); this.routine = new Routine(); } } const workout = new Workout(); console.log(JSON.stringify(workout, null, 4));
.as-console-wrapper { max-height: none !important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.