| by Arround The Web | No comments

How to Convert JSON to/from a Map in JavaScript?

The JSON is a lightweight data integration format that is mainly utilized to store and transport data from one server or system to another. On the other hand, a Map also stores data and it uses the key value format where the key can have any data type. The developer can retrieve specific data by selecting its corresponding key.

This article explains the process to convert JSON to/from a Map in JavaScript by covering the following sections:

How to Convert JSON Data to a Map in JavaScript?

Converting JSON data into a Map preserves the key-value pair format as “Map” and also stores data in the key-value form just like JSON. So, the developer can maintain the original order of the keys which is not guaranteed with JavaScript object conversion. Converting “JSON” data into “Map” offers more flexibility and allows the developer to use Map built-in methods to provide easiness while traversing over the data.

Let’s visit the below code block where the JSON hard-coded data is going to be converted into a Map:

 <script type="text/javascript">
  const jsonFormat = '{"author1":"Jackson","author2":"Reed","author3":"Tasha","author4":"Petterson"} ';

  const mapFormat = new Map(Object.entries(JSON.parse(jsonFormat)));

  console.log(mapFormat);
 </script>

The explanation of the above code is stated as:

  • First, create a const type variable named “jsonFormat” containing data in JSON format i.e. in the key-value format.
  • Next, create a new instance of the Map with the name “mapFormat”. To parse the JSON data, pass the “mapFormat” inside the “JSON.parse()” method.
  • Then, pass the result returned by this method into the “Object.entries()” to create an array of arrays and each inner array represents the key-value pairs.
  • Pass the end result or all these methods along proper alignment inside the “Map” constructor. Now, its instance “mapFormat” contains the converted JSON data which gets displayed over the console window using the “console.log()” method.

After the compilation of the above code, the console window will look like this:

The output confirms that the JSON data has been converted into Map. For further information and examples to convert JSON data into an array or Map, you can visit our other article.

How to Convert JSON Data From a Map in JavaScript?

Converting data into JSON format enhances its lifetime availability and allows you to send this data anywhere over the network without losing data. Moreover, the JSON format is easily human-readable and can be used in web API or configuration files. In the below program, the Map data is going to be converted into the JSON format:

<script type="text/javascript">
 const mapFormat = new Map([
  ['author1', 'Jackson'],
  ['author2', 'Reed'],
  ['author3', 'Tasha'],
  ['author4', 'Petterson'],
 ]);

 const jsonFormat = JSON.stringify(Object.fromEntries(mapFormat));
 console.log(jsonFormat);
</script>

The explanation of the above code block is stated as:

  • First, the instance named “mapFormat” is created for the Map that contains several entries.
  • Next, the “Object.fromEntries()” method is utilized and the “mapFormat” is passed to it. This will convert the provided Map data into a nested array.
  • Then, the nested array is passed to the “JSON.stringify()” method to convert the nested array into the JSON format while preserving the alignment of the key-value pair.
  • In the end, the generated JSON format data gets displayed over the console window.

The output generated after the compilation of the above code is shown below:

The output shows that the Map data is now converted into the JSON format successfully.

How to Fetch JSON API and Convert its Data Into Map?

The JSON data received from the API can also be directly converted into Map by utilizing the same approach described above in the first section. To do this, the API needs to be first fetched then the fetched JSON data gets converted into the Map, as shown below:

<script>
async function convertJSONApi() {
 try {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/');
  const jsonFormat = await res.json();

  const mapFormat = new Map(Object.entries(jsonFormat));
  console.log(mapFormat);
 } catch (causeError) {
  console.error('Error fetching or converting data:', causeError);
 }
}

   convertJSONApi();
</script>

The description of the above code is stated below:

  • First, the asynchronous function named “convertJSONApi()” is defined by utilizing the keyword “async” behind the function “keyword”.
  • Next, use the “try” block and create a “const” type variable “res” that will store the fetched data from the API. The fetching is done by inserting the API link inside the “fetch()” method. Also, attach the “await” keyword behind this “fetch()” method to wait for the arrival of all the API data.
  • Then, apply the “json()” method on the “res” variable to read all received or fetched data. The “await” keyword is also applied behind it to wait for the completion of reading the data. Pass the result in the variable named “jsonFormat”.
  • After that, the “jsonFormat” is passed inside the method named “Object.entries()” to create a nested array for provided data. This is then passed inside the “Map()” constructor to convert the arrays into Map and gets stored in the “Map” instance named “mapFormat”.
  • This fetched JSON API which is now converted to Map is then displayed on the console by displaying the “mapFormat” variable inside the “console.log()” method.
  • To catch any caused error during the whole process, utilize the “catch” block and pass a dummy parameter in it that contains occurred errors and to handle it displays a dummy message.

The output after the completion of the above code is shown below:

The output shows that the JSON format data has been retrieved from the provided API and then this data is converted into the Map.

You’ve learned about the process to convert JSON to Map and Map to JSON in JavaScript.

Conclusion

To convert JSON data to Map, methods like “JSON.parse()” and “Object.entries()” are used. The first one parses the JSON data, and the second one creates a nested array of parsed data. In the case of converting Map data to JSON format, the “Object.fromEntries()” and “JSON.stringify()” methods are used that will convert data into a nested array and convert it into JSON format respectively. This blog has explained the procedure to convert JSON to and from a Map in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply