I'd like to start using ES6 Map instead of JS objects but I'm being held back because I can't figure out how to JSON.stringify()
a Map
. My keys are guaranteed to be strings and my values will always be listed. Do I really have to write a wrapper method to serialize?
12 Answers
Both JSON.stringify
and JSON.parse
support a second argument. replacer
and reviver
respectively. With replacer and reviver below it's possible to add support for native Map object, including deeply nested values
function replacer(key, value) {
if(value instanceof Map) {
return {
dataType: 'Map',
value: Array.from(value.entries()), // or with spread: value: [...value]
};
} else {
return value;
}
}
function reviver(key, value) {
if(typeof value === 'object' && value !== null) {
if (value.dataType === 'Map') {
return new Map(value.value);
}
}
return value;
}
Usage:
const originalValue = new Map([['a', 1]]);
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);
Deep nesting with combination of Arrays, Objects and Maps
const originalValue = [
new Map([['a', {
b: {
c: new Map([['d', 'text']])
}
}]])
];
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);
-
7Just marked this as correct. While I don't like the fact you have to "dirty up" the data across the wire with a non-standardized
dataType
, I can't think of a cleaner way. Thanks.– rynopOct 9, 2020 at 18:07 -
@rynop yeah it's more like a little program with it's own data storage format than just using pure native functionality– PawelOct 9, 2020 at 21:52
-
2
-
1@JimiDini good point, updated. Now if someone wants to declare these as arrow functions it won't mess with the scope– PawelJan 27, 2021 at 9:35
-
1@mkoe sure, but the probability of that is somewhere between being hit by a lightning and being hit by a lightning while hiding in a basement– PawelSep 3, 2021 at 13:40
You can't directly stringify the Map
instance as it doesn't have any properties, but you can convert it to an array of tuples:
jsonText = JSON.stringify(Array.from(map.entries()));
For the reverse, use
map = new Map(JSON.parse(jsonText));
-
11This does not convert to a JSON object, but instead to an Array of arrays. Not the same thing. See Evan Carroll's answer below for a more complete answer. May 8, 2019 at 14:52
-
8@SatThiru An array of tuples is the customary representation of
Map
s, it goes well with the constructor and iterator. Also it is the only sensible representation of maps that have non-string keys, and object would not work there.– BergiMay 8, 2019 at 16:42 -
Bergi, please note that OP said "My keys are guaranteed to be strings". May 10, 2019 at 17:20
-
9@SatThiru In that case, use
JSON.stringify(Object.fromEntries(map.entries()))
andnew Map(Object.entries(JSON.parse(jsonText)))
– BergiMay 10, 2019 at 17:43 -
3@Drenai Then don't use
Obect.fromEntries
, and use the code from my main answer instead of the one from the comment. The code that builds an object literal was in response to Sat Thiru, who gave the case that the keys are strings.– BergiMar 13, 2020 at 18:22
You can't.
The keys of a map can be anything, including objects. But JSON syntax only allows strings as keys. So it's impossible in a general case.
My keys are guaranteed to be strings and my values will always be lists
In this case, you can use a plain object. It will have these advantages:
- It will be able to be stringified to JSON.
- It will work on older browsers.
- It might be faster.
-
43
-
12"It might be faster" - Do you have any source on that? I'm imagining a simple hash-map must be faster than a full blown object, but I have no proof. :)– LillemanFeb 11, 2016 at 18:01
-
1@Xplouder That test uses expensive
hasOwnProperty
. Without that, Firefox iterates objects much faster than maps. Maps are still faster on Chrome, though. jsperf.com/es6-map-vs-object-properties/95– OriolMar 18, 2016 at 13:49 -
1True, seems that Firefox 45v iterates objects away faster than Chrome +49v. However Maps still wins vs objects in Chrome.– XplouderMar 18, 2016 at 19:52
-
1Just passing by and figure out my problem thanks to this. I really wish to move to a farm and leave all this behind, sometimes.– napoluxAug 10, 2020 at 14:38
While there is no method provided by ecmascript yet, this can still be done using JSON.stingify
if you map the Map
to a JavaScript primitive. Here is the sample Map
we'll use.
const map = new Map();
map.set('foo', 'bar');
map.set('baz', 'quz');
Going to an JavaScript Object
You can convert to JavaScript Object literal with the following helper function.
const mapToObj = m => {
return Array.from(m).reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
JSON.stringify(mapToObj(map)); // '{"foo":"bar","baz":"quz"}'
Going to a JavaScript Array of Objects
The helper function for this one would be even more compact
const mapToAoO = m => {
return Array.from(m).map( ([k,v]) => {return {[k]:v}} );
};
JSON.stringify(mapToAoO(map)); // '[{"foo":"bar"},{"baz":"quz"}]'
Going to Array of Arrays
This is even easier, you can just use
JSON.stringify( Array.from(map) ); // '[["foo","bar"],["baz","quz"]]'
-
> Going to an JavaScript Object < Shouldn't it have code to handle keys such as
__proto__
? Or you can damage the entire environment by trying to serialize such a map. Alok's response doesn't suffer from this, I believe.– roimOct 29, 2021 at 23:40
Using spread sytax Map can be serialized in one line:
JSON.stringify([...new Map()]);
and deserialize it with:
let map = new Map(JSON.parse(map));
-
7This'll work for a one-dimensional Map, but not for an n-dimensional map.– mattsvenMay 12, 2020 at 19:01
Given your example is a simple use case in which keys are going to be simple types, I think this is the easiest way to JSON stringify a Map.
JSON.stringify(Object.fromEntries(map));
The way I think about the underlying data structure of a Map is as an array of key-value pairs (as arrays themselves). So, something like this:
const myMap = new Map([
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
]);
Because that underlying data structure is what we find in Object.entries, we can utilize the native JavaScript method of Object.fromEntries()
on a Map as we would on an Array:
Object.fromEntries(myMap);
/*
{
key1: "value1",
key2: "value2",
key3: "value3"
}
*/
And then all you're left with is using JSON.stringify() on the result of that.
-
-
-
@Megajin
Object.fromEntries()
is non-destructive, so you will still have your original Map intact. Apr 6 at 7:35 -
@AlokSomani yes, you are right. However if you want to parse a JSON (or the newly created Object) back, it won't work.– MegajinApr 6 at 12:12
A Better Solution
// somewhere...
class Klass extends Map {
toJSON() {
var object = { };
for (let [key, value] of this) object[key] = value;
return object;
}
}
// somewhere else...
import { Klass as Map } from '@core/utilities/ds/map'; // <--wherever "somewhere" is
var map = new Map();
map.set('a', 1);
map.set('b', { datum: true });
map.set('c', [ 1,2,3 ]);
map.set( 'd', new Map([ ['e', true] ]) );
var json = JSON.stringify(map, null, '\t');
console.log('>', json);
Output
> {
"a": 1,
"b": {
"datum": true
},
"c": [
1,
2,
3
],
"d": {
"e": true
}
}
Hope that is less cringey than the answers above.
-
I'm not sure that many will be satisfied with extending the core map class just to serialize it to a json...– vasiaApr 5, 2020 at 21:36
-
2They don't have to be, but it's a more SOLID way of doing it. Specifically, this aligns with the LSP and OCP principles of SOLID. That is, the native Map is being extended, not modified, and one can still use Liskov Substitution (LSP) with a native Map. Granted, it's more OOP than a lot of novices or staunch Functional Programming people would prefer, but at least it's beset upon a tried & true baseline of fundamental software design principles. If you wanted to implement Interface Segregation Principle (ISP) of SOLID, you can have a small
IJSONAble
interface (using TypeScript, of course).– CodyApr 5, 2020 at 22:47
Stringify a Map
instance (objects as keys are OK):
JSON.stringify([...map])
or
JSON.stringify(Array.from(map))
or
JSON.stringify(Array.from(map.entries()))
output format:
// [["key1","value1"],["key2","value2"]]
Below solution works even if you have nested Maps
function stringifyMap(myMap) {
function selfIterator(map) {
return Array.from(map).reduce((acc, [key, value]) => {
if (value instanceof Map) {
acc[key] = selfIterator(value);
} else {
acc[key] = value;
}
return acc;
}, {})
}
const res = selfIterator(myMap)
return JSON.stringify(res);
}
-
Without testing your answer, I already appreciate how it brings attention to the problem of nested Maps. Even if you successfully convert this to JSON, any parsing done in the future has to have explicit awareness that the JSON was originally a
Map
and (even worse) that each sub-map (it contains) was also originally a map. Otherwise, there's no way to be sure that anarray of pairs
isn't just intended to be exactly that, instead of a Map. Hierarchies of objects and arrays do not carry this burden when parsed. Any proper serialization ofMap
would explicitly indicate that it is aMap
. Nov 30, 2019 at 6:53 -
The very simple way.
const map = new Map();
map.set('Key1', "Value1");
map.set('Key2', "Value2");
console.log(Object.fromEntries(map));
` Output:-
{"Key1": "Value1","Key2": "Value2"}
-
3Warning: Map can have non-string values as keys. This will not work if your Map keys are non-stringify-able types themselves :
JSON.stringify(Object.fromEntries(new Map([['s', 'r'],[{s:3},'g']])))
becomes'{"s":"r","[object Object]":"g"}'
– asp47Jan 5 at 22:09
Just want to share my version for both Map and Set JSON.stringify only. I'm sorting them, useful for debugging...
function replacer(key, value) {
if (value instanceof Map) {
const reducer = (obj, mapKey) => {
obj[mapKey] = value.get(mapKey);
return obj;
};
return [...value.keys()].sort().reduce(reducer, {});
} else if (value instanceof Set) {
return [...value].sort();
}
return value;
}
Usage:
const map = new Map();
const numbers= new Set()
numbers.add(3);
numbers.add(2);
numbers.add(3);
numbers.add(1);
const chars= new Set()
chars.add('b')
chars.add('a')
chars.add('a')
map.set("numbers",numbers)
map.set("chars",chars)
console.log(JSON.stringify(map, replacer, 2));
Result:
{
"chars": [
"a",
"b"
],
"numbers": [
1,
2,
3
]
}
Although there would be some scenarios where if you were the creator of the map you would write your code in a separate 'src' file and save a copy as a .txt file and, if written concisely enough, could easily be read in, deciphered, and added to server-side.
The new file would then be saved as a .js and a reference to it sent back from the server. The file would then reconstruct itself perfectly once read back in as JS. The beauty being that no hacky iterating or parsing is required for reconstruction.
-
1Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.– Community BotOct 20, 2021 at 13:43
-
2This sounds like a nice 10,000 foot process overview, but an actual implementation would be much more useful.– TylerHOct 20, 2021 at 15:51
-
Well, it was more food for thought really than a total solution. Sorry I'm new here and not sure how to add my code to the comments as yet. Oct 21, 2021 at 3:35
-
[...someMap.entries()].join(';')
; for something more complex you could try something similar using something like[...someMap.entries()].reduce((acc, cur) => acc + `${cur[0]}:${/* do something to stringify cur[1] */ }`, '')
obj[key]
may get you something unexpected. Consider the caseif (!obj[key]) obj[key] = newList; else obj[key].mergeWith(newList);
.