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"]"
JSON. stringify doesn't directly work with sets because the data stored in the set is not stored as properties.
Stringify a JavaScript ArrayIt is also possible to stringify JavaScript arrays: Imagine we have this array in JavaScript: const arr = ["John", "Peter", "Sally", "Jane"]; Use the JavaScript function JSON.
JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans.
stringify() The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
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()));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With