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.
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.parsereviver, we should also allow an options bag as aJSON.stringifyreplacer.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
strictandcallToJSON.Using
strict: truewould cause an error to be emitted whenever one of the following is encountered:null, not created withJSON.rawJSON()undefined, Function, and Symbol valuesInfinityandNaNUsing
callToJSON: falsewould 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 ofstrictcould 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
would throw an error if serialising
xwould not retain all of its information in the resulting JSON.