How to Serialize ES6 Maps for JSON Processing
When making the switch from ES6 Objects to Maps, the inability to directly JSON.stringify a Map can be a hindrance. This article delves into a solution to this challenge, using the second argument of both JSON.stringify and JSON.parse, replacer and reviver, respectively.
Custom Replacer and Reviver Functions
To add support for Maps, custom replacer and reviver functions can be created. These functions handle the conversion to and from JSON:
function replacer(key, value) { if (value instanceof Map) { return { dataType: 'Map', value: Array.from(value.entries()), // or with spread: value: [...value] }; } else { return value; } }
function reviver(key, value) { if (typeof value === 'object' && value !== null) { if (value.dataType === 'Map') { return new Map(value.value); } } return value; }
Usage
With the custom functions in place, serializing and deserializing Maps becomes straightforward:
const originalValue = new Map([['a', 1]]); const str = JSON.stringify(originalValue, replacer); const newValue = JSON.parse(str, reviver); console.log(originalValue, newValue);
Deep Nesting
The technique extends to deeply nested structures composed of Maps, Arrays, and Objects:
const originalValue = [ new Map([['a', { b: { c: new Map([['d', 'text']]) } }]]) ]; const str = JSON.stringify(originalValue, replacer); const newValue = JSON.parse(str, reviver); console.log(originalValue, newValue);
The above is the detailed content of How to Serialize and Deserialize ES6 Maps with JSON.stringify and JSON.parse?. For more information, please follow other related articles on the PHP Chinese website!