Skip to content

Conversation

@skewb1k
Copy link

@skewb1k skewb1k commented Aug 30, 2025

Adds cjson.encode_sort_keys(enabled) option.

If enabled, keys in encoded objects will be sorted in alphabetical order.

Uses the most performant approach to sort keys I could find. A small benchmark with comparisons is available here: https://github.com/skewb1k/lua-c-sort-keys-benchmark.

Fixes #66

@skewb1k skewb1k force-pushed the feat/sort-keys branch 2 times, most recently from 91af5a5 to 51bace7 Compare August 31, 2025 18:54
skewb1k added a commit to skewb1k/neovim that referenced this pull request Aug 31, 2025
Problem: There is no way to ensure a stable key order when encoding a JSON string,
which can be useful for comparisons and producing cleaner diffs.

Solution: Introduce a `sort_keys` option for `vim.json.encode()`,which
is disabled by default. When enabled, object keys are sorted in
alphabetical order.

Adapts PR to upstream: openresty/lua-cjson#115.
@skewb1k skewb1k marked this pull request as ready for review August 31, 2025 19:41
skewb1k added a commit to skewb1k/neovim that referenced this pull request Aug 31, 2025
Problem: There is no way to ensure a stable key order when encoding a JSON string,
which can be useful for comparisons and producing cleaner diffs.

Solution: Introduce a `sort_keys` option for `vim.json.encode()`,which
is disabled by default. When enabled, object keys are sorted in
alphabetical order.

Adapts PR to upstream: openresty/lua-cjson#115.
skewb1k added a commit to skewb1k/neovim that referenced this pull request Sep 9, 2025
Problem: There is no way to ensure a stable key order when encoding a JSON string,
which can be useful for comparisons and producing cleaner diffs.

Solution: Introduce a `sort_keys` option for `vim.json.encode()`,which
is disabled by default. When enabled, object keys are sorted in
alphabetical order.

Adapts PR to upstream: openresty/lua-cjson#115.
@skewb1k
Copy link
Author

skewb1k commented Feb 9, 2026

Rebased on latest master

@justinmk
Copy link

justinmk commented Feb 9, 2026

cc @zhuizhuhaomeng

@zhuizhuhaomeng
Copy link

I will review it when I am free.

@skewb1k
Copy link
Author

skewb1k commented Feb 10, 2026

I changed the memory strategy: encode_keybuf is now persistent between calls (like encode_buf with encode_keep_buffer). It's only allocated or freed when the settings change. What do you think, is this better?

@zhuizhuhaomeng
Copy link

It is better, but we need to free it if it is too large.

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.

cjson.encode() modified order

3 participants