Skip to content

Unexpected JSON.stringify and toJSON behavior #271

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

Closed
kentor opened this issue Jan 2, 2015 · 1 comment
Closed

Unexpected JSON.stringify and toJSON behavior #271

kentor opened this issue Jan 2, 2015 · 1 comment

Comments

@kentor
Copy link

kentor commented Jan 2, 2015

> Immutable = require('immutable')
> Model = Immutable.Record({})
[Function: Record]
> Model.prototype.toJSON = function() { return 'model' }
[Function]
> JSON.stringify({ a: new Model() })
'{"a":"model"}'
> JSON.stringify(Immutable.Map({ a: new Model() }))
'{"a":{}}'

I expected the last line to return '{"a":"model"}'.

I know toJSON on iterables is an alias to toJS and calls toJS recursively which is why the Model's toJSON isn't called at all. Perhaps toJSON should instead call toJSON recursively which gives us a more familiar way to override the serialization behavior?

@leebyron
Copy link
Collaborator

leebyron commented Jan 6, 2015

Thanks for finding this and great suggestion on the fix. I implemented almost exactly what you recommended and added this example as a test case.

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

No branches or pull requests

2 participants