How to convert a Set to JSON in JavaScript


Borislav Hadzhiev

Last updated: Nov 3, 2021


Photo from Unsplash

Convert a Set to JSON in JavaScript #

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']
We had to convert the 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.

This is equivalent to using the 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:

  1. use the JSON.parse() method to parse the JSON string to an array.
  2. pass the array to the Set() constructor
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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.