convert Typescript Map to json string representation












4















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.










share|improve this question

























  • ro[ke] should be ro[key] not sure if that's a typo.

    – James Hay
    Sep 6 '17 at 3:58











  • Where is the Map type coming from ? What library ?

    – Titian Cernicova-Dragomir
    Sep 6 '17 at 5:00











  • es6 "Map" ? Try new Map()

    – Lostfields
    Sep 6 '17 at 5:32
















4















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.










share|improve this question

























  • ro[ke] should be ro[key] not sure if that's a typo.

    – James Hay
    Sep 6 '17 at 3:58











  • Where is the Map type coming from ? What library ?

    – Titian Cernicova-Dragomir
    Sep 6 '17 at 5:00











  • es6 "Map" ? Try new Map()

    – Lostfields
    Sep 6 '17 at 5:32














4












4








4


1






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.










share|improve this question
















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.







javascript json typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 6 '17 at 15:19







breezymri

















asked Sep 6 '17 at 3:31









breezymribreezymri

85521632




85521632













  • ro[ke] should be ro[key] not sure if that's a typo.

    – James Hay
    Sep 6 '17 at 3:58











  • Where is the Map type coming from ? What library ?

    – Titian Cernicova-Dragomir
    Sep 6 '17 at 5:00











  • es6 "Map" ? Try new Map()

    – Lostfields
    Sep 6 '17 at 5:32



















  • ro[ke] should be ro[key] not sure if that's a typo.

    – James Hay
    Sep 6 '17 at 3:58











  • Where is the Map type coming from ? What library ?

    – Titian Cernicova-Dragomir
    Sep 6 '17 at 5:00











  • es6 "Map" ? Try new Map()

    – Lostfields
    Sep 6 '17 at 5:32

















ro[ke] should be ro[key] not sure if that's a typo.

– James Hay
Sep 6 '17 at 3:58





ro[ke] should be ro[key] not sure if that's a typo.

– James Hay
Sep 6 '17 at 3:58













Where is the Map type coming from ? What library ?

– Titian Cernicova-Dragomir
Sep 6 '17 at 5:00





Where is the Map type coming from ? What library ?

– Titian Cernicova-Dragomir
Sep 6 '17 at 5:00













es6 "Map" ? Try new Map()

– Lostfields
Sep 6 '17 at 5:32





es6 "Map" ? Try new Map()

– Lostfields
Sep 6 '17 at 5:32












4 Answers
4






active

oldest

votes


















6














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






share|improve this answer





















  • 2





    With [key, val] instead of the parameter e it would be more readable IMO. :-)

    – Paleo
    Sep 6 '17 at 8:22













  • yeah, I usually forget that nice new destructuring assignment :-) Thanks.

    – Lostfields
    Sep 7 '17 at 8:35



















4














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






share|improve this answer































    0














    Although it does not directly answer your question: when I had the some 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"];





    share|improve this answer

































      -1














      You can also use the ES6 spread-operator for this to convert any ES6 Map with JSON-compatible data to JSON:



      function mapToJson(map) {
      return JSON.stringify([...map]);
      }





      share|improve this answer
























      • But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

        – Robert Jack Will
        Nov 24 '18 at 14:30











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46066343%2fconvert-typescript-mapstring-string-to-json-string-representation%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      6














      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






      share|improve this answer





















      • 2





        With [key, val] instead of the parameter e it would be more readable IMO. :-)

        – Paleo
        Sep 6 '17 at 8:22













      • yeah, I usually forget that nice new destructuring assignment :-) Thanks.

        – Lostfields
        Sep 7 '17 at 8:35
















      6














      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






      share|improve this answer





















      • 2





        With [key, val] instead of the parameter e it would be more readable IMO. :-)

        – Paleo
        Sep 6 '17 at 8:22













      • yeah, I usually forget that nice new destructuring assignment :-) Thanks.

        – Lostfields
        Sep 7 '17 at 8:35














      6












      6








      6







      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






      share|improve this answer















      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







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Sep 7 '17 at 8:36

























      answered Sep 6 '17 at 5:40









      LostfieldsLostfields

      4121412




      4121412








      • 2





        With [key, val] instead of the parameter e it would be more readable IMO. :-)

        – Paleo
        Sep 6 '17 at 8:22













      • yeah, I usually forget that nice new destructuring assignment :-) Thanks.

        – Lostfields
        Sep 7 '17 at 8:35














      • 2





        With [key, val] instead of the parameter e it would be more readable IMO. :-)

        – Paleo
        Sep 6 '17 at 8:22













      • yeah, I usually forget that nice new destructuring assignment :-) Thanks.

        – Lostfields
        Sep 7 '17 at 8:35








      2




      2





      With [key, val] instead of the parameter e it would be more readable IMO. :-)

      – Paleo
      Sep 6 '17 at 8:22







      With [key, val] instead of the parameter e it would be more readable IMO. :-)

      – Paleo
      Sep 6 '17 at 8:22















      yeah, I usually forget that nice new destructuring assignment :-) Thanks.

      – Lostfields
      Sep 7 '17 at 8:35





      yeah, I usually forget that nice new destructuring assignment :-) Thanks.

      – Lostfields
      Sep 7 '17 at 8:35













      4














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






      share|improve this answer




























        4














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






        share|improve this answer


























          4












          4








          4







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






          share|improve this answer













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







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 6 '17 at 15:19









          breezymribreezymri

          85521632




          85521632























              0














              Although it does not directly answer your question: when I had the some 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"];





              share|improve this answer






























                0














                Although it does not directly answer your question: when I had the some 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"];





                share|improve this answer




























                  0












                  0








                  0







                  Although it does not directly answer your question: when I had the some 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"];





                  share|improve this answer















                  Although it does not directly answer your question: when I had the some 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"];






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 24 '18 at 14:36

























                  answered Nov 24 '18 at 14:25









                  Robert Jack WillRobert Jack Will

                  3,62111017




                  3,62111017























                      -1














                      You can also use the ES6 spread-operator for this to convert any ES6 Map with JSON-compatible data to JSON:



                      function mapToJson(map) {
                      return JSON.stringify([...map]);
                      }





                      share|improve this answer
























                      • But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

                        – Robert Jack Will
                        Nov 24 '18 at 14:30
















                      -1














                      You can also use the ES6 spread-operator for this to convert any ES6 Map with JSON-compatible data to JSON:



                      function mapToJson(map) {
                      return JSON.stringify([...map]);
                      }





                      share|improve this answer
























                      • But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

                        – Robert Jack Will
                        Nov 24 '18 at 14:30














                      -1












                      -1








                      -1







                      You can also use the ES6 spread-operator for this to convert any ES6 Map with JSON-compatible data to JSON:



                      function mapToJson(map) {
                      return JSON.stringify([...map]);
                      }





                      share|improve this answer













                      You can also use the ES6 spread-operator for this to convert any ES6 Map with JSON-compatible data to JSON:



                      function mapToJson(map) {
                      return JSON.stringify([...map]);
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 13 '17 at 10:08









                      MatthiasSommerMatthiasSommer

                      527317




                      527317













                      • But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

                        – Robert Jack Will
                        Nov 24 '18 at 14:30



















                      • But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

                        – Robert Jack Will
                        Nov 24 '18 at 14:30

















                      But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

                      – Robert Jack Will
                      Nov 24 '18 at 14:30





                      But this returns a list of pairs (like [["x","apple"],["y","banana"]]) instead of the desire Json object {"x": "apple", "y": "banana" }.

                      – Robert Jack Will
                      Nov 24 '18 at 14:30


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46066343%2fconvert-typescript-mapstring-string-to-json-string-representation%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Costa Masnaga

                      Fotorealismo

                      Sidney Franklin