Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify of object of map return empty

    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 tried:

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

why am I getting the empty object instead of map 1 and map 2 when I use JSON.stringify()?

like image 272
GAK Avatar asked Oct 08 '17 18:10

GAK


People also ask

Why does my JavaScript Object return an empty JSON string?

Instead of converting my JavaScript object into a JSON string, it returned an empty JSON string. Undefined values. In my case, the issue occurred because my object had properties with undefined values. Take a look at the following example, which will reproduce the issue:

How do you stringify a JSON object in JavaScript?

Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What happens when you return a null value from a JSON?

If you return null, null will be added to the JSON string. If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.

How do I remove a function from a JSON object?

In JSON, functions are not allowed as object values. The JSON.stringify () function will remove any functions from a JavaScript object, both the key and the value: This can be omitted if you convert your functions into strings before running the JSON.stringify () function.


2 Answers

This is the expected result. JSON.stringify does not recognize a Map object as anything different than a regular object, and the JSON spec itself does not have a way to properly store a Map. It just treats the map as a regular object, possibly including any own object properties set on it.

var m = new Map();

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

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

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

If you are just using string keys, you could use a regular object instead of a Map.

like image 84
Alexander O'Mara Avatar answered Sep 21 '22 16:09

Alexander O'Mara


With credit to Tim Brown in his blog post on the subject - when the contents of the Map object are serialisable, you can do:

  1. serialise Map to JSON:

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

  2. de-serialise JSON to Map:

    new Map(JSON.parse(jsonStr))

like image 25
Martin CR Avatar answered Sep 20 '22 16:09

Martin CR