This is not possible, and this is expected. If a WeakMap
instance would be serializable (for example to JSON), then you would need to be able to enumerate its keys, but to have the "weak" behaviour, this is not supported.
Mozilla Contributors write the following on WeakMap
(I highlight):
WeakMap
allows associating data to objects in a way that doesn't prevent the key objects from being collected, even if the values reference the keys. However, a WeakMap
doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration; if a WeakMap
exposed any method to obtain a list of its keys, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map
rather than a WeakMap
.
So for instance, it is not even possible to know how many keys a WeakMap
instance currently has, which is of course a requirement if you want to serialize an object.