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

Sort keys when encoding tables #51

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion json.lua
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,21 @@

local json = { _version = "0.1.2" }

-- taken from https://www.lua.org/pil/19.3.html
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end

-------------------------------------------------------------------------------
-- Encode
-------------------------------------------------------------------------------
Expand Down Expand Up @@ -86,7 +101,7 @@ local function encode_table(val, stack)

else
-- Treat as an object
for k, v in pairs(val) do
for k, v in pairsByKeys(val) do
if type(k) ~= "string" then
error("invalid table: mixed or invalid key types")
end
Expand Down
4 changes: 3 additions & 1 deletion test/test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ end)

test("objects", function()
local t = { x = 10, y = 20, z = 30 }
assert( equal( t, json.decode( json.encode(t) ) ) )
local encoded = json.encode(t)
assert( equal( '{"x":10,"y":20,"z":30}', encoded) )
assert( equal( t, json.decode( encoded ) ) )
end)


Expand Down