How to convert a Set to JSON in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

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.

index.js
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.

index.js
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 (...).

index.js
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
index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee