将 Typescript Map<string, string> 转换为 json 字符串表示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46066343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:52:08  来源:igfitidea点击:

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

javascriptjsontypescript

提问by breezymri

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

Map<string, string>在打字稿中有一个变量:

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

I want to convert to json string representation:

我想转换为 json 字符串表示:

'{"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 Mapto a javascript objectfirst and then convert to string:

我尝试了 3 种不同的方法。首先是使用m.toString(). 其次是使用JSON.stringify(m). 两人都回来了{}。我什至尝试先将 转换为Mapjavascript object,然后再转换为字符串:

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.

{}当我尝试在控制台中打印它时,这也返回了。

采纳答案by breezymri

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

我最终放弃了使用 es6 Map 并切换到TSMap,它的tags.toJSON()工作原理。

回答by Lostfields

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

就像@james-hay 指出的那样,你有一个可能使对象为空的错字

回答by Robert Hyman Will

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.

虽然它没有直接回答你的问题:当我遇到同样的问题时,我重新考虑了我对 Map 的使用,并选择了纯 JavaScript 对象。由于 JSON 总是需要字符串作为键,因此 Map 的主要优势之一(任何类型的键)无论如何都会丢失。

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:

Map 的另一个优点是它们允许很好的类型签名,例如Map<String, Array<String>>. 但是这里 TypeScript 的“索引签名”为纯 JavaScript 对象提供了这一点,甚至允许为键命名:

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.

这几乎可以像 Map 一样使用(当然,使用不同的语法),即使嵌套. 我认为当您将对象树转换为 JSON 时,后者非常重要,其中映射可以嵌套在其他任意对象和数组的深处。

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:

或者,TypeScript 也具有Record<K, T>此用例的类型:用作类型映射的普通对象。在上面的例子中,我可以写:

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