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

Add a :sort_keys option to Encoder #136

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

NZKoz
Copy link

@NZKoz NZKoz commented May 22, 2014

This allows people to canonicalize JSON and ensure documents are identical irrespective of the order
keys were added to the underlying Hash. This was covered previously in #7 but in the intervening time Symbol#<=> has shipped so I figured I'd see how hard it was to hack in.

This is mostly provided as a "sounding board" to see if the feature is useful to anyone else, rather than something actually ready for inclusion.. The sorting is pretty hackish as is, it should probably intern then sort rather than sort then intern etc.

This allows people to canonicalize JSON and ensure documents are identical irrespective of the order
keys were added to the underlying Hash.
@brianmario
Copy link
Owner

Yeah I can dig this. I just noticed the golang JSON encoder does this too, probably for similar reasons (consistent output). And the implementation is fine by me 👍

@NZKoz
Copy link
Author

NZKoz commented May 22, 2014

The tests only really work on 1.9 and above, the 1.8 hash ordering is likely to break things but I'm 2.0 everywhere so don't really ... care... It's been so long that I'm not sure if @TobiX had any thoughts on additional test cases to include?

@d
Copy link
Contributor

d commented May 22, 2014

@NZKoz I think the key sorting will work for 1.8 as well coz Hash#keys gives an array, and Array#sort is non-destructive. The tests are only failing because of activesupport which is a benchmark-only dependency.

Jesse

@NZKoz
Copy link
Author

NZKoz commented May 23, 2014

@d the sort will break if they keys contain things other than strings, because the sort happens before the to_s, gets called on them, this is obviously pretty minor and would take some crazy test cases, but I'm sure someone could break it.

@NZKoz
Copy link
Author

NZKoz commented May 23, 2014

Yeah, so there's a test case that fails with the current non-refactored implementation of keys / sorting.

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.

None yet

3 participants