1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
Welcome, fellow coders! In this blog, we’ll see how to convert a map to JSON in JS. Shall we?
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.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.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
Let's 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.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!
Problem
/**
* 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 uses **Object.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 to JSON.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 🚀!
Feel free to reach out!