Skip to main content

How to Convert a Set to and from JSON in JavaScript

When you need to serialize a Set object—for example, to store it in localStorage or send it in an API request—you will run into a common issue: JSON.stringify() does not work on Sets directly. This is because the JSON format has no equivalent data type for a Set.

This guide will explain why this happens and teach you the modern, standard methods for correctly converting a Set to a JSON string and parsing it back into a Set.

The Core Problem: Why JSON.stringify() Fails on a Set

The JSON.stringify() method is designed to work with plain JavaScript objects, arrays, and primitive values. A Set is a complex, iterable object with an internal structure that JSON does not understand. When you try to stringify a Set directly, you get an empty object.

Example of code with error:

const mySet = new Set(['a', 'b', 'c']);

// ⛔️ This does NOT work as expected!
const json = JSON.stringify(mySet);

console.log(json); // Output: "{}" (An empty object, data is lost)

To solve this, we must first convert the Set into an Array, which is a data structure that JSON can correctly represent.

Part 1: How to Convert a Set to a JSON String

The solution is a simple two-step process: Set -> Array -> JSON String.

The logic:

  1. Convert to an Array: Use either the spread syntax ([...mySet]) or Array.from(mySet) to convert the Set into an array.
  2. Stringify the Array: Pass the resulting array to JSON.stringify().

Recommended Solution:

const mySet = new Set(['a', 'b', 'c']);

// Step 1: Convert the Set to an array
const myArray = [...mySet]; // or Array.from(mySet)
console.log('Array:', myArray); // Output: ['a', 'b', 'c']

// Step 2: Stringify the array
const json = JSON.stringify(myArray);
console.log('JSON String:', json); // Output: '["a","b","c"]'

Output:

Array: (3) ['a', 'b', 'c']
JSON String: ["a","b","c"]
note

This can be written as a concise one-liner:

const json = JSON.stringify([...mySet]);

Part 2: How to Convert a JSON String back to a Set

The inverse operation is also a two-step process: JSON String -> Array -> Set.

The logic:

  1. JSON.parse(json): This standard method parses a JSON string, which in this case will produce an array.
  2. new Set(array): The Set constructor can accept an iterable (like an array) to create a new Set from its elements.

Recommended Solution:

const json = '["a","b","c"]';

// Step 1: Parse the JSON string to an array
const myArray = JSON.parse(json);
console.log('Parsed Array:', myArray); // Output: ['a', 'b', 'c']

// Step 2: Create a new Set from the array
const mySet = new Set(myArray);
console.log('Final Set:', mySet); // Output: Set(3) { 'a', 'b', 'c' }

Output:

Parsed Array: (3) ['a', 'b', 'c']
Final Set: Set(3) {'a', 'b', 'c'}
note

This can also be written as a one-liner:

const mySet = new Set(JSON.parse(json));

An Advanced Method: Using a Custom toJSON Method

If you are working with objects that contain Sets, JSON.stringify() can take a "replacer" function to customize its behavior. This is useful for automatically converting Sets to arrays during serialization.

Solution:

const data = {
id: 123,
tags: new Set(['user', 'active']),
};

function replacer(key, value) {
// If the value is a Set, convert it to an Array.
if (value instanceof Set) {
return [...value];
}
// Otherwise, return the value as is.
return value;
}

const json = JSON.stringify(data, replacer);

console.log(json); // Output: '{"id":123,"tags":["user","active"]}'

Output:

{"id":123,"tags":["user","active"]}
note

This is a powerful pattern for handling complex, nested data structures.

Conclusion

Directly serializing a Set to JSON is a common pitfall in JavaScript. The key is to use an Array as an intermediate, JSON-compatible representation.

  • To convert a Set to JSON, first convert it to an array, then stringify: JSON.stringify([...mySet]).
  • To convert JSON back to a Set, first parse the JSON to an array, then create a new Set: new Set(JSON.parse(json)).

By using these modern and idiomatic methods, you can reliably serialize and deserialize Set objects for storage or data transmission.