Borislav Hadzhiev
Wed Nov 03 2021·2 min read
Photo by Johannes Plenio
To convert a Set
to JSON, convert the Set
to an array and pass the result
to the JSON.stringify()
method, e.g. JSON.stringify(Array.from(set))
. The
JSON.stringify
method converts the passed in value to a JSON string and
returns the result.
const set1 = new Set(['a', 'b', 'c']); // ✅ Using Array.from const json1 = JSON.stringify(Array.from(set1)); console.log(json1); // 👉️ '["a", "b", "c"]' // ✅ Using spread syntax (...) const json2 = JSON.stringify([...set1]); console.log(json2); // 👉️ '["a", "b", "c"]'
We used the
Array.from
method to convert a Set
to an array.
The method takes an iterable object and converts it to an array.
const set1 = new Set(['a', 'b', 'c']); console.log(Array.from(set1)); // 👉️ ['a', 'b', 'c']
Set
to an array because Set
objects don't have native support for serialization or parsing.The last step is to use the JSON.stringify method to convert the array to a JSON string.
An alternative to using the Array.from
method is to use the
spread syntax (...).
const set1 = new Set(['a', 'b', 'c']); const json2 = JSON.stringify([...set1]); console.log(json2); // 👉️ '["a", "b", "c"]'
In this example, we used the spread syntax (...) to unpack the values from the
Set
into an array.
Array.from
method, however in some scenarios the spread syntax (...) doesn't play nice with TypeScript.If you need to convert the JSON string to a Set
, you have to:
JSON.parse()
method to parse the JSON string to an array.const set1 = new Set(['a', 'b', 'c']); const json1 = JSON.stringify(Array.from(set1)); console.log(json1); // 👉️ '["a", "b", "c"]' // ✅ Parse back to Set const parsed = new Set(JSON.parse(json1)); console.log(parsed); // 👉️ {'a', 'b', 'c'}
The Set
constructor takes an iterable, such as an array, as a parameter, so we
can pass it the result from calling the JSON.parse
method.