Skip to main content
Modern JavaScript Engineering

JavaScript Map to JSON Serializer & Parser

Safely convert ES6 Map and Set objects into JSON strings and back. Overcome empty {} stringify issues, preserve numeric and object keys, and generate robust replacer and reviver utility code.

Input Object / Map Definition
Generated JavaScript Helper Code

Why JSON.stringify Fails on ES6 Maps and Sets

When JavaScript introduced the Map and Set collection types in ECMAScript 2015 (ES6), it did not update the JSON.stringify algorithm to serialize their contents. If you attempt JSON.stringify(new Map([['a', 1]])), the engine returns {}.

1. Strategy 1: Array of Entries (Recommended)

Because Map keys can be numbers, booleans, or object references, serializing as an entries array guarantees total fidelity:

// Serialization:
const jsonString = JSON.stringify(Array.from(myMap.entries()));

// Deserialization:
const restoredMap = new Map(JSON.parse(jsonString));

2. Strategy 2: Plain Object Conversion

If your Map keys are strings and the receiving REST API expects a conventional JSON dictionary:

// Serialization:
const jsonString = JSON.stringify(Object.fromEntries(myMap));

// Deserialization:
const restoredMap = new Map(Object.entries(JSON.parse(jsonString)));

Frequently Asked Questions

Native JSON.stringify only serializes enumerable own properties of an object. Because ES6 Map stores its key-value pairs in an internal slot rather than enumerable properties, standard JSON.stringify produces {} unless a custom replacer function or Object.fromEntries(map) is used.
Converting non-string keys into standard object keys forces string coercion (e.g. 1 becomes "1"). To preserve types, serialize the Map as an array of key-value pairs using JSON.stringify(Array.from(map.entries())).
If serialized as an object, use new Map(Object.entries(JSON.parse(jsonStr))). If serialized as an entries array, use new Map(JSON.parse(jsonStr)).
Yes. The generated replacer and reviver helpers convert Sets to Arrays and handle BigInt values without throwing TypeError: Do not know how to serialize a BigInt.