Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a Map<string, string> variable in typescript:

let m = Map<string, string>().set('tag', 'v1');

I want to convert to json string representation:

'{"tag": "v1"}'

I've tried 3 different ways. First is to use m.toString(). Second is using JSON.stringify(m). Both returned {}. I've even tried to convert the Map to a javascript object first and then convert to string:

function MapToString(map): string {
  let ro = {};
  Object.keys(map).forEach( key => {
    ro[key] = map[key];
  });
  return JSON.stringify(ro);
}

s = MapToString(m);

This returned {} as well when I tried to print it in the console.

like image 214
breezymri Avatar asked Sep 06 '17 03:09

breezymri


3 Answers

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

like image 159
breezymri Avatar answered Oct 18 '22 02:10

breezymri


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

like image 12
Lostfields Avatar answered Oct 18 '22 03:10

Lostfields


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"];
like image 9
Robert Jack Will Avatar answered Oct 18 '22 02:10

Robert Jack Will