Tuesday, September 4, 2018

Typescript - How to convert Map to/from JSON with examples

Json Map Convert

In Typescript applications, We used to get the use cases where data in map object cast to JSON object or JSON to Map conversions.
In this blog, We are going to learn how to convert Map to JSON or JSON to Map
The map is a data structure introduced in ES6 for storing key and values
JSON is a javascript object notation for the format of key and values enclosed in braces. The same code works in Javascript as this uses Latest Es6 classes and syntax.

How to Convert Map to JSON object  examples 

First Map is created with key and values of type strings
map.forEach method is used iterate the map which contains callback called for every element of Map.
Object created and added keys and values.
Finally, Object is returned in JSON format using 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 is
{"one":"value1","two":"value2","three":"value3"}

How to Convert JSON object to Map with examples

 Created JSON Object which contains key and values Next created Empty map used for...in loop to iterate the JSON object and added key and values to 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);

Related article


EmoticonEmoticon