Skip to content

Add sort_keys option in the generator.#1043

Open
samyron wants to merge 8 commits into
ruby:masterfrom
samyron:sm/sort-keys
Open

Add sort_keys option in the generator.#1043
samyron wants to merge 8 commits into
ruby:masterfrom
samyron:sm/sort-keys

Conversation

@samyron

@samyron samyron commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

I had some time last night so I decided to see how hard it would be to implement a sort_keys option to the generator. This adds support to the C extension, Java extension and truffleruby implementation.

irb(main):005> h = { zzz: true, a: 1, c: 2, b: "Test", 'z': 'blah 2'} 
=> {zzz: true, a: 1, c: 2, b: "Test", z: "blah 2"}
irb(main):006> JSON.generate(h, sort_keys: false)
=> "{\"zzz\":true,\"a\":1,\"c\":2,\"b\":\"Test\",\"z\":\"blah 2\"}"
irb(main):007> JSON.generate(h, sort_keys: true)
=> "{\"a\":1,\"b\":\"Test\",\"c\":2,\"z\":\"blah 2\",\"zzz\":true}"
irb(main):008> JSON.generate(h)
=> "{\"zzz\":true,\"a\":1,\"c\":2,\"b\":\"Test\",\"z\":\"blah 2\"}"

@byroot

byroot commented Jun 25, 2026

Copy link
Copy Markdown
Member

THanks for handling this, however in lieu of #1038, I think a sort_key option shouldn't be a a simple boolean, but should also accept a proc so we can implement custom sorting semantic.

@samyron

samyron commented Jun 25, 2026

Copy link
Copy Markdown
Contributor Author

THanks for handling this, however in lieu of #1038, I think a sort_key option shouldn't be a a simple boolean, but should also accept a proc so we can implement custom sorting semantic.

No problem. I can try to take a stab at that tonight night/this weekend. I think it should be as simple as accepting a proc and passing it to obj.sort_by when generating the JSON.

@samyron

samyron commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

I added the ability to pass a Proc which accepts two [key, value] pairs to allow for arbitrary sorting. I'm not entirely sure if this is what you had in mind but it allows for maximum flexibility. I'm not totally sure if that's warranted but I ran with that assumption. I'm happy to make changes as requested.

Note that a boolean (true) is still supported which will sort keys lexicographically.

irb(main):002> reverse = ->(a, b) { b[0] <=> a[0] }
=> #<Proc:0x000000012d2bbc08 (irb):2 (lambda)>
irb(main):003> JSON.generate({2=>"a", 1=>"b", 3=>"c"}, sort_keys: reverse)
=> "{\"3\":\"c\",\"2\":\"a\",\"1\":\"b\"}"

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