When using JSON.stringify on a map object, it returns an empty result

    var map1= new Map();
    map1.set("one",1);
    var map2 = new Map();
    map2.set("two",2);
   concatMap = {};
   concatMap['one']= map1;
   concatMap['two']= map2;
 JSON.stringify(concatMap);

//outputs : "{"one":{},"two":{}}"

I also attempted the following:

concatMap = {};
concatMap.one= map1;
concatMap.two= map2;

Why do I receive empty objects instead of map1 and map2 when using JSON.stringify()?

Answer №1

The desired outcome is as follows: JSON.stringify does not interpret a Map object any differently than a standard object, and the JSON specification itself lacks a mechanism to accurately store a Map. Instead, it treats the map as a regular object and may include any custom object properties set on it.

var m = new Map();

// This will not be included:
m.set('test', 123);

// This will be included:
m['other'] = 456;

console.log(JSON.stringify(m));

If you only use string keys, consider using a plain object rather than a Map.

Answer №2

Simple solution :

In the scenario where you create a Map like this:

const map = new Map();

and populate it with values using:

map.set('key', 'value');

Calling JSON.stringify on the map will result in an empty object being displayed.

To rectify this issue, you can use the following approach:

const objFromMap = Object.fromEntries(map);
JSON.stringify(objFromMap);

Dealing with complex objects :

If your object contains a field that is a map, for instance:

class MyClazz {
   field = new Map();
}
const instance = new MyClazz();
instance.field.set('k', 'v');

When using JSON.stringify, the output will be:

{field: {}}

To resolve this, you need to override the toJSON method as shown below:

class MyClazz {
   field = new Map();
   toJSON(): this {
      return {
          field: Object.fromEntries(this.field),
      }
   }
}
const instance = new MyClazz();
instance.field.set('k', 'v');

After implementing this change, calling JSON.stringify(instance); will give the desired output:

{field: {k: 'v'}}

Answer №3

Credit goes to Tim Brown for sharing a helpful tip in his blog post. He suggests that when the data within a Map object is serializable, you can follow these steps:

  1. Convert Map to JSON:

    JSON.stringify(Array.from(map.entries()))

  2. Convert JSON back to Map:

    new Map(JSON.parse(jsonStr))

Answer №4

It has been pointed out by others that Maps are not currently supported by JSON. However, 2D arrays can be used instead:

const map1 = new Map().set("one", 1),
           map2 = new Map().set("two", 2),
           concatMap = {
              one: [...map1],
              two: [...map2]
           };

const result = JSON.stringify(concatMap);

To decode this information, you can use the following:

 let {one, two} = JSON.parse(result);
 one = new Map(one),
 two = new Map(two);

Answer №5

Utilize the following code snippet to create a new Map:

const newMap = JSON.parse('{}');
newMap[name] = value;

After assigning values, remember to stringify the newMap. The end result will be parsed as a Map<string, string>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Yii2 pjax not refreshing properly when updating records in the gridview

I have successfully implemented functionality in my grid-view to control the number of rows displayed per page. This feature includes a drop-down menu with options such as 5, 10, 25, 50, and 100 rows. Whenever a user selects an option from the drop-down, I ...

The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging ou ...

Issue Loading Bodies with Box2D and LibGDX: BodyEditorLoader Problem

Currently, I am using the most recent version of LibGDX which is 0.9.9. After creating a JSON file through Physics Body Editor 2.9.2, I attempted to load it into my game by adding this code: BodyEditorLoader loader = new BodyEditorLoader(Gdx.files ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

AngularJS and Gulp: Enhancing Static Assets with Revisioning

I have implemented the gulp-rev module to re-vision static assets in my source files. It generates new file names for CSS, JS, and HTML files by appending a hash code to it. Before : app.js After : app-2cba45c.js The issue I am facing is that in my An ...

Issue: EACCES error encountered while attempting to execute bower install operation

After running bower install css-circle-menu, I encountered the following error: /usr/local/lib/node_modules/bower/lib/node_modules/configstore/index.js:54 throw err; ^ Error: EACCES: permission denied, open '/Users/ja ...

Reading a JSON object from a SQL database and transforming it into a Java class: A step-by-step guide

I have set up a column of type varchar(max) in the table within my Database, utilizing 'for JSON Auto' to store all the columns of that table as a JSON object, including Foreign keys. The JSON I generated now appears like this: { "widge ...

Creating enduring designs in Next.js

I've been diving into this amazing article and I'm puzzling over the implementation of persistence in Option 4. It seems like you would need to redefine the .getLayout method for each page. I'm uncertain about how nesting logic is handled fo ...

Object displaying no visible illumination

Recently, I've been experimenting with this project, and after some trial and error, I've managed to get things working to some extent. As a novice in JavaScript, I'm unsure if the issue I'm facing has a simple solution. The problem is ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...

Puppeteer and Chromium are ready to go with no need for any configuration

I have a specific HTTP request that I am trying to intercept, but I am encountering issues when chromium is launched through puppeteer. Some flags seem to be causing the requests to not return the expected data. However, everything works fine when I manual ...

Guide to developing a personalized useReducer with integrated decision-making and event activation

I am interested in creating a custom hook called useTextProcessor(initialText, props). This hook is designed for managing and manipulating text (string) within a React state. It utilizes useReducer to maintain a cumulative state. Here is the implementation ...

Choosing Tags with Ajax in Select2

The JSON data below is fetched from /tags: [ { "id": "CSS", "text": "CSS" }, { "id": "HTML", "text": "HTML" }, { "id": "JavaScript", "text": "JavaScript" }, { "id": "jQuer ...

efficiency of a process during ng-repeat execution

Do you see a distinction in how ng-repeat is written in these two examples? <div ng-repeat="item in getItems()"> Versus this: <div ng-repeat="item in items"> Imagine getItems is structured like this: $scope.getItems = function() { return ...

Turn off the validation of individual JavaScript errors in Eclipse

Currently, I am exploring the use of Eclipse for JavaScript within the "Eclipse IDE for Java EE Developers" package. In my project, there is a heavy reliance on Bluebird, a promises implementation, resulting in several lines like: somePromise.catch(funct ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Unable to read a QR code from a blob link

After spending countless hours searching Google and SO, I still haven't found a solution on how to scan a QR code in my Java based Selenium tests. I've tried various methods but encountered errors along the way. Attempted to use the ZXing libr ...

How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my fac ...

The navigation buttons on the Bootstrap carousel will only respond to keyboard commands after the arrow on the

Is there a way to change the default behavior of the bootstrap carousel to allow keyboard navigation without having to click the arrows on the screen first? In my modal, I have a carousel that I want users to be able to navigate using the keyboard arrows ...

The value returned by a component should remain consistent regardless of where it is invoked. Additionally, the main component in React should not re-render when the state of a sub-component is

I am looking to have the same value displayed in the Home function from the Component, without causing a rerender when the useState in Component is updated. import { useState, useEffect } from "react"; function Component() { const [count, setC ...