Implementing an identical JSON.stringify

Allen Wirfs-Brock allen at wirfs-brock.com
Sun Aug 5 22:41:00 UTC 2018



> On Aug 4, 2018, at 9:47 PM, Darien Valentine <valentinium at gmail.com <mailto:valentinium at gmail.com>> wrote:
> 
> > I guess what confused me is that it would detect a [[NumberData]] internal slot, but instead of unboxing to that value it tries to ducktype call .valueOf on the object. So the presence of [[NumberData]] changes the behavior even if it does not actually use this value.

Fundamentally, the tests are trying to determine which values are supposed to be serialized as JSON primitive values and which need to be serialized as JSON objects (or arrays). The assumption in JSON stingify is that JS wrapper objects for numbers, strings, and booleans should be serialized as primitive values.

The ES JSON functions were based upon Crockford's original JSON 2 API and his implementation of it as it existed in mid 2008 (https://web.archive.org/web/20090213004934/http://www.json.org/json2.js <https://web.archive.org/web/20090213004934/http://www.json.org/json2.js>). Crockford, in his design,  made the decisions that the wrapper objects should serialize as primitives. In his implementation he accomplished that adding toJSON methods to the prototypes of Number, String, and Boolean. The body of those methods were: return this.valueOf();

In ES5, we wanted to avoid having to add a bunch of toJSON methods to the builtins (Date was the exception). So, we needed a cross-realm way to test for those primitive wrapper values. In ES1-5 the way to do that was to test the  value of the [[Class]] internal property which was set for all built-in objects. If a Number or Stream wrapper [[Class]] value was detected, we did an internal ToNumber or ToString to get the primitive value. This is equivalent to what the built-in valueOf methods do. 

In ES6, [[Class]] was eliminated as a specification device because it was confusing and starting to be misused. I realized that (for specification purposes) we could describe the equivalent test as a test for an internal slot that was unique to each kind of wrapper.  So, the [[Class]] test was replaced with tests for [[NumberData]], [[StringDate]], and [[BooleanData]]. That specification change should not be observable to JS code.  I didn’t change the ToNumber and ToString calls because that would have been a potentially observable change.

> 
> This surprised me too initially, but I think we can infer a rationale if we read between the lines a bit. A similar pattern appears in the JSON stringify algorithm itself (as opposed to the SerializeJSONProperty algorithm) when interpreting the "space" argument. So it might seem to be that it’s a peculiarity of how JSON-related operations are defined — but I don’t think that’s the pattern. What these two cases have in common is that either a numeric value or a string value would be valid: neither hint would be more correct. In the case of SerializeJSONProperty, this is because both string values and numeric values are valid JSON values; in the case of stringify’s space argument, it’s because this is overloaded to either specify a number of spaces or a whitespace string. In the absence of a reason to weight one to-primitive operation over another, it sniffs for the singular unambiguous clue about type that’s really available, the slot.

Yes, this is correct.  It is because of overload resolution. Crockford’s original implementation only recognized primitive Numbers or Strings as the 3rd argument. Any object, including wrapper objects, passed as the 3rd argument were ignored. I thought that wrapper objects should also be accepted so I introduced the sequence you see in the spec. which is similar to what was also done in SerializeJSONProperty.

In retrospect is might have been better to have followed Crockford’s example. It’s very unlike that a wrapper object would ever be passed as that argument.  It’s probably more likely that an object with a bespoke valueOf or toString might be passed and the algorithm, as specified, ignores such objects..

Allen


> 
> Why doesn’t it then just use the slot value directly? Because this would depart from expectations about the @@toPrimitive / toValue / toString contract that is honored everywhere else, I believe.
> 
> On Sun, Aug 5, 2018 at 12:30 AM Michael Theriot <michael.lee.theriot at gmail.com <mailto:michael.lee.theriot at gmail.com>> wrote:
> Regarding cases like Reflect.construct(Number, [], String), the reason this throws is because the ToNumber algorithm calls ToPrimitive if its operand is an object. This in turn will call String.prototype.valueOf on the object which does not have [[StringData]]. There’s nothing funny going on, it’s just a weird effect in aggregate. You would just need to implement all the steps here — internal ops like ToNumber, ToPrimitive, etc. It’s not that it "considers type", but rather that these algorithms will call methods by specific names on objects they receive. String.prototype and Object.prototype both implement "valueOf", but only the former will fail the slot check.
> 
> Thanks for demystifying this. I never realized it was just ducktyping .valueOf on the object.
> 
> ```js
> Number.prototype.valueOf = () => 0;
> 
> JSON.stringify(1); // 1
> JSON.stringify(new Number(1)); // 0
> ```
> 
> I guess what confused me is that it would detect a [[NumberData]] internal slot, but instead of unboxing to that value it tries to ducktype call .valueOf on the object. So the presence of [[NumberData]] changes the behavior even if it does not actually use this value.
> 
> On Sat, Aug 4, 2018 at 10:14 PM Darien Valentine <valentinium at gmail.com <mailto:valentinium at gmail.com>> wrote:
> Is this a question about how/if one could replicate its behavior in theory from ES code, or are you suggesting a change to the existing behavior for these exotic cases?
> 
> Assuming the former:
> 
> The relevant steps are [here](https://tc39.github.io/ecma262/#sec-serializejsonproperty <https://tc39.github.io/ecma262/#sec-serializejsonproperty>). The `instanceof` a value isn’t significant in this algorithm, just its slots (if it is an object) or its primitive type. So one can handle number and string by leveraging branded checks as you’ve shown — nothing more is needed than branded methods and typeof to manage that one.
> 
> However it is ultimately not possible to replicate because there is no possible brand test for [[BooleanData]].
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org <mailto:es-discuss at mozilla.org>
> https://mail.mozilla.org/listinfo/es-discuss <https://mail.mozilla.org/listinfo/es-discuss>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org <mailto:es-discuss at mozilla.org>
> https://mail.mozilla.org/listinfo/es-discuss

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180805/a1a6619d/attachment.html>


More information about the es-discuss mailing list