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.
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
JSON.stringify(Array.from(map.entries())).
new Map(Object.entries(JSON.parse(jsonStr))). If serialized as an entries array, use new Map(JSON.parse(jsonStr)).
TypeError: Do not know how to serialize a BigInt.