For AI agents: the complete documentation index is available at /tc39-atlas/en/llms.txt, the full documentation bundle is available at /tc39-atlas/en/llms-full.txt, and this page is available as Markdown at /tc39-atlas/en/proposals/year/pending/set-map-prototype-tojson.md.
  • English
  • {Set,Map}.prototype.toJSON ?

    Proposal details
    Proposal overview

    The proposal addresses the unhelpful output of JSON.stringify on Map and Set instances, which currently returns '{}'. It suggests adding default toJSON methods to Set.prototype and Map.prototype, so that JSON serialization returns an array of entries or values respectively. Userland code can still override these methods on specific instances.

    Note

    The README below comes from the upstream repository and may contain outdated stage or status metadata. Use the proposal details above as the current source of truth.

    Map-Set.prototype.toJSON

    An ECMAScript proposal. Currently at Stage 0.

    This proposal was brought before the committee in the March 2016 meeting, and thoroughly rejected. Details

    Problem

    Here is the current situation:

    var s = new Set(['yo', 'ya', true, 8]);
    
    console.log(JSON.stringify(s)); // '{}'

    This result is unhelpful. Same goes for Map.

    Proposal

    This proposal is about providing a sensible default to the common operation of JSON serialization via default toJSON implementations on Set.prototype and Map.prototype. Of course, userland code can always shadow this value on specific instances.

    Map.prototype.toJSON

    The essence of the proposal is captured in this snippet (spec in markdown or HTML):

    Map.prototype.toJSON = function toJSON() {
      return [...Map.prototype.entries.call(this)];
    }

    Set.prototype.toJSON

    The essence of the proposal is captured in this snippet (spec in markdown or HTML):

    Set.prototype.toJSON = function toJSON() {
      return [...Set.prototype.values.call(this)];
    }

    Discussion

    There might be a web compat concern if code using native Map and Set or polyfill relies on the current JSON.stringify behavior.

    Licence

    This work is dedicated to the public domain. It is CC0 licenced.