JSON stringify a Set

MitMaro picture MitMaro · Jul 2, 2015 · Viewed 31k times · Source

How would one JSON.stringify() a Set?

Things that did not work in Chromium 43:

var s = new Set(['foo', 'bar']);

JSON.stringify(s); // -> "{}"
JSON.stringify(s.values()); // -> "{}"
JSON.stringify(s.keys()); // -> "{}"

I would expect to get something similar to that of a serialized array.

JSON.stringify(["foo", "bar"]); // -> "["foo","bar"]"

Answer

Oriol picture Oriol · Jul 2, 2015

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()));