Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Convert a String to enum in TypeScript?
Next article icon

How to Convert Map to JSON in TypeScript ?

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using JSON.stringify
  • Using fast-json-stringify Library
  • Using json-stringify-safe Library
  • Using mapToObj Method
  • Using a Custom Replacer Function for JSON.stringify

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:

PS

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"}

Next Article
How to Convert a String to enum in TypeScript?

G

gauravgandal
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences