你怎么JSON。stringify ES6地图吗?(复制)

时间:2022-09-26 06:49:31

This question already has an answer here:

这个问题已经有了答案:

I'd like to start using ES6 Map instead of JS objects but I'm being held back because I can't figure out how to JSON.stringify() a Map. My keys are guaranteed to be strings and my values will always be lists. Do I really have to write a wrapper method to serialize?

我想开始使用ES6映射而不是JS对象,但是由于我不知道如何使用JSON.stringify()映射,我被限制了。我的键是字符串,我的值总是列表。我真的需要编写一个包装器方法来序列化吗?

1 个解决方案

#1


32  

You can't.

你不能。

The keys of a map can be anything, including objects. But JSON syntax only allows strings as keys. So it's impossible in a general case.

地图的键可以是任何东西,包括对象。但是JSON语法只允许字符串作为键。所以在一般情况下是不可能的。

My keys are guaranteed to be strings and my values will always be lists

我的键是字符串,我的值总是列表

In this case, you can use a plain object. It will have these advantages:

在这种情况下,可以使用普通对象。它将具有以下优点:

  • It will be able to be stringified to JSON.
  • 它将能够被绑定到JSON。
  • It will work on older browsers.
  • 它将适用于旧的浏览器。
  • It might be faster.
  • 可能会更快。

#1


32  

You can't.

你不能。

The keys of a map can be anything, including objects. But JSON syntax only allows strings as keys. So it's impossible in a general case.

地图的键可以是任何东西,包括对象。但是JSON语法只允许字符串作为键。所以在一般情况下是不可能的。

My keys are guaranteed to be strings and my values will always be lists

我的键是字符串,我的值总是列表

In this case, you can use a plain object. It will have these advantages:

在这种情况下,可以使用普通对象。它将具有以下优点:

  • It will be able to be stringified to JSON.
  • 它将能够被绑定到JSON。
  • It will work on older browsers.
  • 它将适用于旧的浏览器。
  • It might be faster.
  • 可能会更快。