Jonas
Jonas

Reputation: 7945

JSON.stringify not stringifying the whole object

JSON.stringify(this.workout)is not stringifying the whole object. workoutis an object from the class Workout which looks like this:

export class Workout {
    id: string;
    name: string;
    exercises: Exercise[];
    routine: Routine;
}

Exercise and Routine is another Class with also nested arrays.

The problem is JSON.stringify(this.workout) return only {"name":"Day 1"}. Any ideas where the problem could be?

Upvotes: 2

Views: 2677

Answers (2)

Danziger
Danziger

Reputation: 21191

As you can see in this example with plain JS, it works as expected, so you should review your code and make sure all the objects are properly initialised.

Alternatively, you can also implement a custom toJSON method in any of those classes to define how you want to serialise them (check the example in 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;
}

Upvotes: 1

Brad
Brad

Reputation: 163603

For any classes you wish to serialize, you may have to define your to toJSON() method to ensure the data is serialized. Otherwise, only the regular enumerable properties are going to end up in the output.

You'll probably need this on Exercise and Routine as well as Workout.

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Upvotes: 2

Related Questions