tc39 / proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
https://tc39.github.io/proposal-json-parse-with-source
MIT License
213 stars 9 forks source link

Reusability of raw serialization mechanism #19

Closed gibson042 closed 2 years ago

gibson042 commented 2 years ago

toJSON provides a capability available to any object for controlling its serialization, and a well-known Symbol would extend that capability to include raw output (e.g., JSON.stringify({toJSON(){ return {[Symbol.rawJSON]: longStringOfDigits}; }})).

Alternatively, the mechanism for raw output could be limited to each individual invocation of JSON.stringify or even to each individual invocation of a replacer function, either of which would have the potential benefit of coupling it to specifically-expressed author intent.

bakkot commented 2 years ago

Using a symbol would impose a cost (an additional Get) on every existing serialization, which seems bad. Here's an alternative I brought up on the matrix:

Add a new JSON.rawString which returns an opaque, frozen, null-prototype object with a new internal slot holding a string (which has been checked to be valid JSON - probably even a valid JSON primitive, to prevent adding weird whitespace and duplicate keys and so on). This can be called by any code. If JSON.stringify encounters such an object, it serializes it to its internal slot.

This also requires a cost (checking for presence of an internal slot) on every serialization, but the cost is much lower.


I kind of like this approach. It (as well as the well-known symbol approach, by contrast to the per-invocation approaches) allows you to do stuff like

class Rational {
  // constructor etc elided
  #num = 1n;
  #denom = 1n;
  toJSON() {
    return { type: 'rational', num: JSON.rawString(String(this.#num)), denom: JSON.rawString(String(this.#denom)) };
  }
}

which, while it is a new capability, seems like it is OK?

bakkot commented 2 years ago

Re: the above: @rbuckton raises that if we use the above approach we would probably also want a JSON.isRawString so that custom serializers could use this, which I think I agree with.