Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON stringify a Set

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"]" 
like image 606
MitMaro Avatar asked Jul 02 '15 17:07

MitMaro


People also ask

Can you JSON Stringify a set?

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

Can you JSON Stringify an array?

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.

Does JSON Stringify work on objects?

JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans.

What does JSON Stringify () method do?

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.


2 Answers

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())); 
like image 173
Oriol Avatar answered Oct 07 '22 11:10

Oriol


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

like image 37
tanguy_k Avatar answered Oct 07 '22 11:10

tanguy_k