Welcome, fellow coders! In this blog, we’ll see how to convert a map to JSON in JS. Shall we?
Method 1: JSON.stringify
This method takes an object, and through the magic of serialization, transforms it into a JSON string.
const myMap = new Map([
['key1', 'value1'],
['key2', { nestedKey: 'nestedValue' }],
['key3', function() { console.log('Gotcha!'); }],
]);
const jsonString = JSON.stringify(Object.fromEntries(myMap));
console.log(jsonString);
// Output: {"key1":"value1","key2":{"nestedKey":"nestedValue"}}
// Gotcha! (Function is omitted during serialization) ⚠
Explanation:
Object.fromEntries(myMap)
converts the Map into an object.JSON.stringify()
then transforms the object into a JSON string.- ⚠ Common Gotcha: Ensure your Map only contains serializable values. Non-serializable items (like functions) will be omitted during the conversion.
Method 2: Array.from()
Array.from() assists in converting a Map to an array of key-value pairs, which can then be easily transformed into JSON.
const myMap = new Map([
['key1', 'value1'],
['key2', { nestedKey: 'nestedValue' }],
]);
myMap.set(myMap, 'Circular reference gotcha!');
const jsonArray = Array.from(myMap);
const jsonString = JSON.stringify(jsonArray);
console.log(jsonString);
// Output: [["key1","value1"],["key2",{"nestedKey":"nestedValue"}]]
// Circular reference gotcha! (⚠ Circular references are not supported)
Explanation:
Array.from(myMap)
creates an array of key-value pairs from the Map.JSON.stringify()
converts the array into a JSON string.- Circular references within the Map are not supported and will result in an error:
- A circular reference occurs when an object references itself, either directly or indirectly through a chain of references. See below sample code:
- In above code example,
myMap
contains a circular reference where the Map references itself, resulting in a circular structure. JSON.stringify
does not support circular references, and attempting to stringify an object with a circular reference will throw an error.- Circular references can be identified and avoided by properly structuring your data to avoid self-referencing loops.
// Circular reference example:
// obj contains a property circularRef that points back to the object itself.
const obj = {};
obj.circularRef = obj; // Circular reference
- ⚠ Common Gotcha: Ensure your Map’s keys and values are serializable, and watch out for circular references, as they are not supported during JSON conversion.
JSON.parse(): The Reverse -> JSON to Map
Lets see the reverse, we use JSON.parse() to convert a JSON string back to a Map.
const jsonString = '{"key1":"value1","key2":{"nestedKey":"nestedValue"}}';
const parsedMap = new Map(Object.entries(JSON.parse(jsonString)));
console.log(parsedMap);
// Output: Map { 'key1' => 'value1', 'key2' => { nestedKey: 'nestedValue' } }
Explanation:
JSON.parse(jsonString)
transforms the JSON string into an object.Object.entries()
creates an array of key-value pairs.- We then use the Map constructor to build the Map.
- ⚠ Note: Always verify if parsed JSON is correctly represented in Javascript data structures, like nested objects, arrays, etc.
🧪Practice Coding Problem: JSON Treasure Hunt 🏴☠️
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Ahoy, aspiring JSON pirates! Your ship is filled with a treasure trove of Maps, and you need to convert them into JSON to navigate the digital seas. Write a function
mapToJSON(map)
that takes a Map as input and returns a JSON string representing the Map’s key-value pairs. But beware, not all treasures are easy to convert!JavaScript/** * Convert a Map to JSON string, handling tricky treasures! * @param {Map} map - The Map to convert. * @returns {string} - The JSON string representing the Map. */ function mapToJSON(map) { // > > > 👉 Write code here 👈 < < < } // ⚠ Tricky Treasure Map #1: Nested Objects const trickyMap1 = new Map([ ['key1', 'value1'], ['key2', { nestedKey: 'nestedValue' }], ]); console.log(mapToJSON(trickyMap1)); // Output: '{"key1":"value1","key2":{"nestedKey":"nestedValue"}}' // ⚠ Tricky Treasure Map #2: Circular References const trickyMap2 = new Map([ ['key1', 'value1'], ]); trickyMap2.set(trickyMap2, 'Circular reference challenge!'); console.log(mapToJSON(trickyMap2)); // Output: '{"key1":"value1"}' (Circular reference skipped) // ⚠ Tricky Treasure Map #3: Function Gotcha! const trickyMap3 = new Map([ ['key1', 'value1'], ['key2', function() { console.log('Gotcha!'); }], ]); console.log(mapToJSON(trickyMap3)); // Output: '{"key1":"value1"}' (Function excluded)
Please attempt before seeing the Answer:
function mapToJSON(map) {
const seen = new WeakSet();
function replacer(key, value) {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return; // Skip circular references
}
seen.add(value);
}
if (typeof value === 'function') {
return; // Skip functions
}
return value;
}
return JSON.stringify(Object.fromEntries(map), replacer);
}
Explanation:
- The
mapToJSON
function usesObject.fromEntries(map)
to convert the Map into a serializable object. - To handle circular references, a
seen
WeakSet is used to track objects already visited during the JSON stringification process. - The
replacer
function is passed toJSON.stringify()
to customize the serialization process. It skips circular references and functions. - The resulting JSON string represents the Map, excluding any circular references or non-serializable items.
Now you can easily convert your Javascript Map data into JSON , and ship it across your apps.
Happy data shipping⚓ and keep coding 🚀!