How to Convert Map to JSON in TypeScript ?
Last Updated : 24 Jul, 2024
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion.
Using JSON.stringify
In this approach, we are using the JSON.stringify method to convert a TypeScript Map into a JSON-formatted string. By iterating over the map entries and creating an object with key-value pairs, the output JSON string (res) prints the map data in a serialized format.
Syntax:
JSON.stringify(value: any, replacer?:
(key: string, value: any) =>
any, space?: string | number): string;
Example: The below example uses JSON.stringify to convert the map to JSON in TypeScript.
JavaScript const data: Map<string, string> = new Map([ ['name', 'GeeksforGeeks'], ['type', 'Education'], ['category', 'Computer Science'], ]); const obj: { [key: string]: string } = {}; data.forEach((value, key) => { obj[key] = value; }); const res: string = JSON.stringify(obj); console.log(res);
Output:
{ name: "GeeksforGeeks", type: "Education", category: "Computer Science"}
Using fast-json-stringify Library
In this approach, we are using the fast-json-stringify library to efficiently generate a JSON stringify function with a predefined schema based on the key-value pairs of a Map. The schema is dynamically generated using Array.from(data.entries()).reduce, ensuring that each key is associated with the string type. Finally, the stringify function is applied to the converted object created from the Map, generate the JSON output.
Steps to use fast-json-stringify library with TypeScript:
Step 1: Initialize a New Project
Open your terminal or command prompt and navigate to the directory where you want to create your TypeScript project. Then run the following command.
npm init
Step 2: Install TypeScript as a dev dependency
You need to install TypeScript as a dev dependency in your project using the below command.
npm install typescript --save-dev
Step 3: Create a tsconfig.json file
The tsconfig.json file contains TypeScript compiler options for your project. Run the following command.
npx tsc --init
Step 4: Install fast-json-stringify
Install the fast-json-stringify library using the below command.
npm install fast-json-stringify
Step 5: Install node types
Install the @types/node into your project directory using the below command.
npm install --save @types/node
Step 6: Compile TypeScript Code
Use below command to compile TypeScript code.
npx tsc
Step 7: Run Your Code
Use the below command to run the code.
node index.js
Project Structure:

Example: The below example uses fast-json-stringify library to convert the map to JSON in TypeScript.
JavaScript const fastJsonStringify = require('fast-json-stringify'); const data: Map<string, string> = new Map([ ['name', 'GeeksforGeeks'], ['type', 'Education'], ['category', 'Computer Science'], ]); const temp = fastJsonStringify({ type: 'object', properties: Array.from(data.entries()).reduce( (acc: Record<string, { type: string }>, [key, value]) => { acc[key] = { type: 'string' }; return acc; }, {}), }); const res = temp(Object.fromEntries(data)); console.log(res);
Output:
Using json-stringify-safe Library
In this approach, we are using the json-stringify-safe library to convert a TypeScript Map to JSON. We first convert the Map into a plain object using the forEach method, and then apply json-stringify-safe to get the JSON string representation.
Steps to use json-stringify-safe library with TypeScript:
Step 1: Initialize a New Project
Open your terminal or command prompt and navigate to the directory where you want to create your TypeScript project. Then run the following command.
npm init
Step 2: Install TypeScript as a dev dependency
You need to install TypeScript as a dev dependency in your project using the below command.
npm install typescript --save-dev
Step 3: Create a tsconfig.json file
The tsconfig.json file contains TypeScript compiler options for your project. Run the following command.
npx tsc --init
Step 4: Install json-stringify-safe
Install the json-stringify-safe library using the below command.
npm install json-stringify-safe
Step 5: Install node types
Install the @types/node into your project directory using the below command.
npm install --save @types/node
Step 6: Compile TypeScript Code
Use below command to compile TypeScript code.
npx tsc
Step 7: Run Your Code
Use the below command to run the code.
node index.js
Project Structure:

Example: The below example uses json-stringify-safe library to convert the map to JSON in TypeScript.
JavaScript const stringify = require('json-stringify-safe'); const data: Map<string, string> = new Map([ ['name', 'GeeksforGeeks'], ['type', 'Education'], ['category', 'Computer Science'], ]); const obj: { [key: string]: string } = {}; data.forEach((value, key) => { obj[key] = value; }); const jsonString: string = stringify(obj); console.log(jsonString);
Output:
Using mapToObj Method
This approach defines a mapToObj function that iterates over the Map's entries, assigning each key-value pair to an object. Then, it returns the resulting object. Finally, you can stringify the resulting object using JSON.stringify() if you need a JSON string representation.
Example: In this example we defines a function mapToObj() to convert a Map to an object, then demonstrates its usage by converting a Map to a JSON string. It converts a Map to an object and stringifies it.
JavaScript // Define a function to convert Map to object function mapToObj(map: Map<any, any>): { [key: string]: any } { const obj: { [key: string]: any } = {}; map.forEach((value, key) => { obj[key] = value; }); return obj; } // Example usage const data: Map<string, string> = new Map([ ['name', 'GeeksforGeeks'], ['type', 'Education'], ['category', 'Computer Science'], ]); const jsonObject = mapToObj(data); const jsonString = JSON.stringify(jsonObject); console.log(jsonString);
Output:
{"name":"GeeksforGeeks","type":"Education","category":"Computer Science"}
Using a Custom Replacer Function for JSON.stringify
In this approach, we utilize a custom replacer function within the JSON.stringify method to handle the serialization of a Map to JSON. This method allows us to directly convert the Map to a JSON-formatted string without the need for external libraries or additional steps.
Example: The following example demonstrates how to use a custom replacer function to convert a Map to JSON in TypeScript.
JavaScript function mapToJsonWithReplacer(map: Map<any, any>): string { return JSON.stringify(map, (key, value) => { if (value instanceof Map) { return Array.from(value.entries()).reduce((obj, [key, val]) => { obj[key] = val; return obj; }, {}); } return value; }); } const myMap = new Map<string, string>([ ["name", "GeeksforGeeks"], ["type", "Education"], ["category", "Computer Science"] ]); const jsonString = mapToJsonWithReplacer(myMap); console.log(jsonString);
Output:
{"name":"GeeksforGeeks","type":"Education","category":"Computer Science"}
Similar Reads
How to Convert String to JSON in TypeScript ?
Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript: Table of Content Convert String to JSON Using JSON.parse()Convert String
6 min read
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC. Table of Content Using new Date()Using Date.parse() Using Date.UTC()Using new Date()In this appro
2 min read
How to Convert a String to enum in TypeScript?
In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript. These are the two approaches that can be used to solve it: Table of Content
5 min read
How to Convert String to Number in TypeScript?
In TypeScript, converting a string to a number is a common operation that can be accomplished using several different methods. Each method offers unique advantages and can be chosen based on the specific requirements of your application. Below are the approaches to convert string to number in TypeSc
4 min read
How to Convert String to Boolean in TypeScript ?
In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it. There are several approaches to convert string to boolean in TypeScript which are as follows: Table of Content Using Conditional StatementUsing JSON.parse() MethodU
4 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsi
5 min read
How to Convert a Set to an Array in TypeScript ?
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
5 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
4 min read
How to Convert Map to JSON in JavaScript ?
In JavaScript, when working with data, you might encounter situations where you need to convert a Map object into a JSON format. This can be useful for sending data over the network, storing data in local storage, or interfacing with APIs that expect JSON data. Converting a Map to JSON means convert
3 min read
How to Convert Typescript Dictionary to String ?
In TypeScript, dictionaries are often represented as the objects where keys are associated with the specific values. Converting a TypeScript dictionary to a string is an important task when doing API calls where we cast the JSON response from the API to a string. Below are the ways to convert a Type
5 min read