Typescript - How to convert Map to/from JSON with examples| Javascript example

In TypeScript applications, we often encounter scenarios where we need to convert data between a Map object and a JSON object.

In this blog, we will explore how to perform conversions between a Map and JSON. The Map is a data structure introduced in ES6 for storing key-value pairs.

JSON (JavaScript Object Notation) is a format for representing data consisting of key-value pairs enclosed in braces. This code works in JavaScript as it utilizes the latest ES6 classes and syntax.

Now, let’s delve into the various methods for performing these conversions.

How to Convert a Map into a JSON Object using TypeScript’s Iterative Stringify Method

First, we create a Map with keys and values of type strings. Then, we use the map.forEach method to iterate through the map, where a callback is called for every element of the map. We create an object and add keys and values to it. Finally, we return the object in JSON format using the JSON.stringify()method.

let map = new Map<string, string>();
map.set("one", "value1");
map.set("two", "value2");
map.set("three", "value3");
let jsonObject = {};
map.forEach((value, key) => {
  jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject));

Output:

{"one":"value1","two":"value2","three":"value3"}

How to Convert a Map into a JSON Object using TypeScript’s ES6 Object fromEntries Method

ES6 introduced the fromEntries method in the object class. fromEntries takes the input map and converts keys and values into a JSON object.

let map = new Map<string, string>();
map.set("one", "value1");
map.set("two", "value2");
map.set("three", "value3");
const result = Object.fromEntries(map);

console.log(result);

Output:

{
  "one": "value1",
  "two": "value2",
  "three": "value3"
}

Now, let’s discuss ways to convert JSON to a Map object.

How to Convert a JSON Object to a Map using TypeScript’s For-In Loop Iteration

First, we create a JSON object containing keys and values. Next, we create an empty map using a for…in loop to iterate through the JSON object and add keys and values to the map instance.

let jsonObject = { one: "value1", two: "value2", three: "value3" };
let map = new Map<string, string>();
for (var value in jsonObject) {
  map.set(value, jsonObject[value]);
}
console.log("map:" + map.size);

How to Convert a JSON Object to a Map using TypeScript’s ES6 Entries Method

The Object.entries method introduced in ES6 converts a JSON object to a Map in JavaScript and TypeScript.

let jsonObject = { one: "value1", two: "value2", three: "value3" };
const result = Object.entries(jsonObject);
console.log(result);

Summary

In summary, we have learned multiple ways to convert JSON objects to/from Maps in TypeScript and JavaScript.