JSON stringify a Set

后端 未结 3 1923
难免孤独
难免孤独 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:22

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

    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()));
    

提交回复
热议问题