Is implementing toJSON() method enough to make any class instance serializable?

Viewed 69

First quote from Redux doc:

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store.

But what exactly makes an arbitrary object serializable? I do have toJSON() method implemented in the class. Does it suffice?

1 Answers

By definition: Object serialization is the process of converting an object’s state to a string from which it can later be restored.

So basically, any arbitrary object (including nested objects) is serializable.

The point of this statement in Redux docs is that your store should not contain files and byte values in JavaScript TypedArrays. Since they cannot be fully restored from the serialized string.

Consider the example below:

const typedArray = new Int8Array(8);
typedArray1 instanceof Int8Array; // true

const obj = JSON.parse(JSON.stringify(typedArray)); // serialize and deserialize
obj instanceof Int8Array; // false
Related