Skip to content

Commit

Permalink
Improved table encoding code to handle sparse arrays. Floating point …
Browse files Browse the repository at this point in the history
…numbers are encoding improved.
  • Loading branch information
aryajur committed Jul 19, 2020
1 parent dbf4b2d commit ad6ac0f
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions json.lua
Original file line number Diff line number Diff line change
Expand Up @@ -64,32 +64,36 @@ local function encode_table(val, stack)
if stack[val] then error("circular reference") end

stack[val] = true
-- Check whether to treat as a array or object
local array = true
local length = 0
for k in pairs(val) do
if type(k) ~= "number" or k<=0 then
array = nil
break -- Treat as object
else
if k > length then
length = k
end
end
end

if rawget(val, 1) ~= nil or next(val) == nil then
-- Treat as array -- check keys are valid and it is not sparse
local n = 0
for k in pairs(val) do
if type(k) ~= "number" then
error("invalid table: mixed or invalid key types")
end
n = n + 1
end
if n ~= #val then
error("invalid table: sparse array")
end
if array then
-- Encode
for i, v in ipairs(val) do
table.insert(res, encode(v, stack))
for i=1,length do
table.insert(res, encode(val[i], stack))
end
stack[val] = nil
return "[" .. table.concat(res, ",") .. "]"

else
-- Treat as an object
for k, v in pairs(val) do
--[[
if type(k) ~= "string" then
error("invalid table: mixed or invalid key types")
end
]]
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end
stack[val] = nil
Expand All @@ -108,7 +112,7 @@ local function encode_number(val)
if val ~= val or val <= -math.huge or val >= math.huge then
error("unexpected number value '" .. tostring(val) .. "'")
end
return string.format("%.14g", val)
return tostring(val)
end


Expand Down

1 comment on commit ad6ac0f

@alexandro-rezakhani
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to resolve issue #19.

Please sign in to comment.