Skip to content

call toJSON only AFTER this.replacer #45

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

michele-nuzzi
Copy link

replacer needs to be called before toJSON.

example when encoding Buffer I'd like to receive hex strings, but instead toJSON is called and my replacer is not called on Buffers

replacer needs to be called before `toJSON`.

example when encoding `Buffer` I'd like to receive hex strings, but instead `toJSON` is called and my replacer is not called on `Buffer`s
@Faleij
Copy link
Owner

Faleij commented Feb 22, 2025

I understand why you want this but the original implementation of JSON.stringify by Douglas Crockford and the implementation that is in all browsers follows the convention of calling toJSON before the replacer function, that's why this library follows that convention as well.

I will accept a pull request that changes this behavior depending on an argument to JsonStreamStringify so that it does not break the original behavior.

Example of this behavior in chromium browsers:

< JSON.stringify({ toJSON() { return 'toJSON'; }}, (k, v) => {
  console.log({ k, v });
  return v;
})
> {k: '', v: 'toJSON'}

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 this pull request may close these issues.

2 participants