convert Typescript Map<string, string> to json string representation

Readable? No, but it works

JSON.stringify(
  Array.from(
    new Map().set('tag', 'v1').set('foo', 'bar').entries()
  )
  .reduce((o, [key, value]) => { 
    o[key] = value; 

    return o; 
  }, {})
)

Like @james-hay pointed out, you have a typo that probably makes the object empty


I eventually gave up on using es6 Map and switched to TSMap, on which tags.toJSON() works.


Although it does not directly answer your question: when I had the same problem, I reconsidered my use of Map and went for plain JavaScript objects. Since JSON always needs strings as keys, one of Map's main advantages (keys of any type) are lost anyway.

Another advantage of Map is that they allow a nice type signature, like Map<String, Array<String>>. But here TypeScript's "index signatures" provide exactly this for plain JavaScript objects and even allow a name for keys:

interface CityLists {
    [postcode: string]: Array<string>
};

This can be used almost like a Map (with different syntax, of course) and it directly converts to JSON even when nested. I think the latter is quite important when you convert an object tree to JSON where maps can be nested somewhere deep down in other arbitrary objects and arrays.

Alternatively, TypeScript also has the type Record<K, T> for this use-case: a plain object used as a typed map. In the above example, I could write:

let cityLists: Record<string, Array<string>>;
cityLists["capitals"] = ["Rome", "Paris", "Berlin"];