JSON stringify a Set

后端 未结 3 1925
难免孤独
难免孤独 2020-11-30 01:08

How would one JSON.stringify() a Set?

Things that did not work in Chromium 43:

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

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


        
3条回答
  •  没有蜡笔的小新
    2020-11-30 01:32

    Use this JSON.stringify replacer:

    (because toJSON is a legacy artifact, and a better approach is to use a custom replacer, see 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]}"
    

提交回复
热议问题