Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reusability of raw serialization mechanism #19

Closed
gibson042 opened this issue Oct 26, 2021 · 2 comments · Fixed by #22
Closed

Reusability of raw serialization mechanism #19

gibson042 opened this issue Oct 26, 2021 · 2 comments · Fixed by #22

Comments

@gibson042
Copy link
Collaborator

gibson042 commented Oct 26, 2021

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
Copy link

bakkot commented Oct 26, 2021

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
Copy link

bakkot commented Oct 26, 2021

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.

gibson042 added a commit to gibson042/proposal-json-parse-with-source that referenced this issue May 28, 2022
gibson042 added a commit that referenced this issue May 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants