JSON stringify a Set

You can pass a "replacer" function to JSON.stringify:

const fooBar = {
  foo: new Set([1, 2, 3]),
  bar: new Set([4, 5, 6])
};

JSON.stringify(
  fooBar,
  (_key, value) => (value instanceof Set ? [...value] : value)
);

Result:

"{"foo":[1,2,3],"bar":[4,5,6]}"

toJSON is a legacy artifact, and a better approach is to use a custom replacer, see https://github.com/DavidBruant/Map-Set.prototype.toJSON/issues/16


JSON.stringify doesn't directly work with sets because the data stored in the set is not stored as properties.

But you can convert the set to an array. Then you will be able to stringify it properly.

Any of the following will do the trick:

JSON.stringify([...s]);
JSON.stringify([...s.keys()]);
JSON.stringify([...s.values()]);
JSON.stringify(Array.from(s));
JSON.stringify(Array.from(s.keys()));
JSON.stringify(Array.from(s.values()));