trxcllnt commented on issue #14973:
URL: https://github.com/apache/arrow/issues/14973#issuecomment-1363568418

   `toString()` and `toJSON()` are actually really subtle. JS will invoke an 
instance's `toString()` method when implicitly converting a type to a string 
representation, and will use `toJSON()` when running through `JSON.stringify()`.
   
   I know `toJSON()` sounds like it should return a string, but according to 
[the 
docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description)
 `toJSON()` should return the value to be serialized, not a string:
   > If the value has a `toJSON()` method, it's responsible to define what data 
will be serialized. Instead of the object being serialized, the value returned 
by the `toJSON()` method when called will be serialized.
   
   For example:
   ```shell
   # Implicitly converting an Array to a string:
   > `${[new Date(), 5, {}, {foo:1, bar: 'baz'}]}`
   'Thu Dec 22 2022 19:02:07 GMT-0800 (Pacific Standard Time),5,[object 
Object],[object Object]'
   
   # Stringify'ing JSON
   > JSON.stringify([new Date(), 5, {}, {foo:1, bar: 'baz'}])
   '["2022-12-23T03:00:46.440Z",5,{},{"foo":1,"bar":"baz"}]'
   ```
   
   We can override this via custom `toString()` and `toJSON()` implementations:
   ```shell
   > `${[new Date(), 5, {}, {foo:1, bar: 'baz', __proto__: {toString() { return 
JSON.stringify(this); }}}]}`
   'Thu Dec 22 2022 19:00:16 GMT-0800 (Pacific Standard Time),5,[object 
Object],{"foo":1,"bar":"baz"}'
   
   > JSON.stringify([new Date(), 5, {}, {foo:1, bar: 'baz', __proto__: 
{toJSON() { return {foo: this.foo}; }}}])
   '["2022-12-23T03:01:35.003Z",5,{},{"foo":1}]'
   ```
   
   The implementations we provide in Arrow are intended to follow these 
semantics. If you want stringified JSON, why not add a `Table.toJSON()` method 
that returns an Array, then call `JSON.stringify(table.toJSON())`?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to