JSON.stringify for ES6 Maps
When migrating from JavaScript objects to ES6 Maps, JSON.stringify support becomes essential. This article addresses the challenge of serializing Maps for JSON transmission.
Utilizing JSON.stringify Replacer
JSON.stringify offers a second argument, replacer, which can enhance its functionality. Define a replacer function that handles Map objects:
function replacer(key, value) { if(value instanceof Map) { return { dataType: 'Map', value: Array.from(value.entries()), }; } else { return value; } }
Deserialization with JSON.parse Reviver
Likewise, JSON.parse also has a reviver argument to customize object creation during deserialization:
function reviver(key, value) { if(typeof value === 'object' && value !== null) { if (value.dataType === 'Map') { return new Map(value.value); } } return value; }
Usage
To serialize and deserialize an ES6 Map using these functions:
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 replacer and reviver can handle deeply nested data structures containing arrays, objects, and maps:
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 Can I Serialize and Deserialize ES6 Maps with JSON.stringify and JSON.parse?. For more information, please follow other related articles on the PHP Chinese website!