How to convert a WeakMap to a JSON Object in Javascript?

96 views Asked by At

Given a JS WeakMap, I want to convert this to JSON data.

const weakmap = new WeakMap() // Convert weakmap to JSON data / JS object

I've tried JSON.parse(JSON.stringify(weakmap)) which returns empty object. Since one cannot iterate over keys of WeakMap, it's also not possible to convert it by iteration.

1

There are 1 answers

0
trincot On

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.