convert Typescript Map 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.
javascript json typescript
add a comment |
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
ro[ke]
should bero[key]
not sure if that's a typo.
– James Hay
Sep 6 '17 at 3:58
Where is theMap
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
add a comment |
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
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
javascript json typescript
edited Sep 6 '17 at 15:19
breezymri
asked Sep 6 '17 at 3:31
breezymribreezymri
85521632
85521632
ro[ke]
should bero[key]
not sure if that's a typo.
– James Hay
Sep 6 '17 at 3:58
Where is theMap
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
add a comment |
ro[ke]
should bero[key]
not sure if that's a typo.
– James Hay
Sep 6 '17 at 3:58
Where is theMap
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
add a comment |
4 Answers
4
active
oldest
votes
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
2
With[key, val]
instead of the parametere
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
add a comment |
I eventually gave up on using es6 Map and switched to TSMap, on which tags.toJSON()
works.
add a comment |
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"];
add a comment |
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]);
}
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
2
With[key, val]
instead of the parametere
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
add a comment |
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
2
With[key, val]
instead of the parametere
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
add a comment |
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
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
edited Sep 7 '17 at 8:36
answered Sep 6 '17 at 5:40
LostfieldsLostfields
4121412
4121412
2
With[key, val]
instead of the parametere
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
add a comment |
2
With[key, val]
instead of the parametere
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
add a comment |
I eventually gave up on using es6 Map and switched to TSMap, on which tags.toJSON()
works.
add a comment |
I eventually gave up on using es6 Map and switched to TSMap, on which tags.toJSON()
works.
add a comment |
I eventually gave up on using es6 Map and switched to TSMap, on which tags.toJSON()
works.
I eventually gave up on using es6 Map and switched to TSMap, on which tags.toJSON()
works.
answered Sep 6 '17 at 15:19
breezymribreezymri
85521632
85521632
add a comment |
add a comment |
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"];
add a comment |
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"];
add a comment |
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"];
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"];
edited Nov 24 '18 at 14:36
answered Nov 24 '18 at 14:25
Robert Jack WillRobert Jack Will
3,62111017
3,62111017
add a comment |
add a comment |
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]);
}
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
add a comment |
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]);
}
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
add a comment |
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]);
}
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]);
}
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
ro[ke]
should bero[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