Javascript JSON 字符串化一个集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31190885/
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-08-23 06:21:28  来源:igfitidea点击:

JSON stringify a Set

javascriptjsonecmascript-6

提问by MitMaro

How would one JSON.stringify()a Set?

一个JSON.stringify()怎么会是一个Set

Things that did not work in Chromium 43:

在 Chromium 43 中不起作用的事情:

var s = new Set(['foo', 'bar']);

JSON.stringify(s); // -> "{}"
JSON.stringify(s.values()); // -> "{}"
JSON.stringify(s.keys()); // -> "{}"

I would expect to get something similar to that of a serialized array.

我希望得到类似于序列化数组的东西。

JSON.stringify(["foo", "bar"]); // -> "["foo","bar"]"

回答by Oriol

JSON.stringifydoesn't directly work with sets because the data stored in the set is not stored as properties.

JSON.stringify不直接使用集合,因为存储在集合中的数据不存储为属性。

But you can convert the set to an array. Then you will be able to stringify it properly.

但是您可以将集合转换为数组。然后,您将能够正确地对其进行字符串化。

Any of the following will do the trick:

以下任何一项都可以解决问题:

JSON.stringify([...s]);
JSON.stringify([...s.keys()]);
JSON.stringify([...s.values()]);
JSON.stringify(Array.from(s));
JSON.stringify(Array.from(s.keys()));
JSON.stringify(Array.from(s.values()));

回答by tanguy_k

Use this JSON.stringifyreplacer:

使用这个JSON.stringify替代品:

(because toJSONis a legacy artifact, and a better approach is to use a custom replacer, see https://github.com/DavidBruant/Map-Set.prototype.toJSON/issues/16)

(因为toJSON是遗留工件,更好的方法是使用 customreplacer,请参阅https://github.com/DavidBruant/Map-Set.prototype.toJSON/issues/16

function Set_toJSON(key, value) {
  if (typeof value === 'object' && value instanceof Set) {
    return [...value];
  }
  return value;
}

Then:

然后:

const fooBar = { foo: new Set([1, 2, 3]), bar: new Set([4, 5, 6]) };
JSON.stringify(fooBar, Set_toJSON)

Result:

结果:

"{"foo":[1,2,3],"bar":[4,5,6]}"

回答by Stephen Bolton

While all of the above work I suggest that you subclass set and add a toJSONmethod to make sure that it stringify's correctly. Especially if you are going to be stringifying often. I use sets in my Redux stores and needed to make sure this was never a problem.

尽管上述所有工作,我建议您将 set 子类化并添加一个toJSON方法以确保它正确地字符串化。特别是如果您要经常进行字符串化。我在我的 Redux 存储中使用集合,需要确保这从来都不是问题。

This is a basic implementation. Naming is just to illustrate the point pick your own style.

这是一个基本的实现。命名只是为了说明选择你自己的风格。

class JSONSet extends Set {
    toJSON () {
        return [...this]
    }
}

const set = new JSONSet([1, 2, 3])
console.log(JSON.stringify(set))