Skip to content

Commit bdcbc3b

Browse files
committed
feat(json): sort_keys option to vim.json.encode()
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.
1 parent 1cb1cfe commit bdcbc3b

File tree

5 files changed

+269
-49
lines changed

5 files changed

+269
-49
lines changed

runtime/doc/lua.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3375,6 +3375,8 @@ vim.json.encode({obj}, {opts}) *vim.json.encode()*
33753375
• indent: (string) (default "") String used for indentation at
33763376
each nesting level. If non-empty enables newlines and a
33773377
space after colons.
3378+
• sort_keys: (boolean) (default false) Sort object keys in
3379+
alphabetical order.
33783380

33793381
Return: ~
33803382
(`string`)

runtime/doc/news.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ LUA
264264
|vim.list.bisect()| for binary search.
265265
• Experimental `vim.pos` and `vim.range` for Position/Range abstraction.
266266
|vim.json.encode()| has an `indent` option for pretty-formatting.
267+
|vim.json.encode()| has an `sort_keys` option.
267268

268269
OPTIONS
269270

runtime/lua/vim/_meta/json.lua

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,5 +40,7 @@ function vim.json.decode(str, opts) end
4040
--- characters "/" in string values.
4141
--- - indent: (string) (default "") String used for indentation at each nesting level.
4242
--- If non-empty enables newlines and a space after colons.
43+
--- - sort_keys: (boolean) (default false) Sort object
44+
--- keys in alphabetical order.
4345
---@return string
4446
function vim.json.encode(obj, opts) end

0 commit comments

Comments
 (0)