Skip to content

JSON.stringify replacer options bag #12

Description

@eemeli

This might be enough scope creep to be better handled as a separate proposal, but similarly to allowing for an options bag as a JSON.parse reviver, we should also allow an options bag as a JSON.stringify replacer.

The replacer argument currently only handles Function and Array values, so introducing new behaviour for an Object value should not break user code, esp. if we only check for explicitly supported option values.

The two specific options that I think we should add are strict and callToJSON.

Using strict: true would cause an error to be emitted whenever one of the following is encountered:

  • Objects with a prototype other than Array, Object or null, not created with JSON.rawJSON()
  • undefined, Function, and Symbol values
  • The numbers Infinity and NaN
  • Arrays with named properties
  • Objects with symbol-keyed properties

Using callToJSON: false would disable the check for and calling of a .toJSON() method on the values being serialised.

The overall intent here is to allow for JSON.stringify() to be used in a way where anything not matching the supported features of JSON would throw, rather than being silently ignored or transformed. The behaviour of strict could currently be user-implementable with a custom replacer, but disabling calling .toJSON() would require monkeypatching Date and Temporal prototypes, which seems inadvisable.

With something like this in place, calling

JSON.stringify(x, { strict: true, callToJSON: false })

would throw an error if serialising x would not retain all of its information in the resulting JSON.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions