Skip to content

Commit ad6ac0f

Browse files
committed
Improved table encoding code to handle sparse arrays. Floating point numbers are encoding improved.
1 parent dbf4b2d commit ad6ac0f

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

Diff for: json.lua

+19-15
Original file line numberDiff line numberDiff line change
@@ -64,32 +64,36 @@ local function encode_table(val, stack)
6464
if stack[val] then error("circular reference") end
6565

6666
stack[val] = true
67+
-- Check whether to treat as a array or object
68+
local array = true
69+
local length = 0
70+
for k in pairs(val) do
71+
if type(k) ~= "number" or k<=0 then
72+
array = nil
73+
break -- Treat as object
74+
else
75+
if k > length then
76+
length = k
77+
end
78+
end
79+
end
6780

68-
if rawget(val, 1) ~= nil or next(val) == nil then
69-
-- Treat as array -- check keys are valid and it is not sparse
70-
local n = 0
71-
for k in pairs(val) do
72-
if type(k) ~= "number" then
73-
error("invalid table: mixed or invalid key types")
74-
end
75-
n = n + 1
76-
end
77-
if n ~= #val then
78-
error("invalid table: sparse array")
79-
end
81+
if array then
8082
-- Encode
81-
for i, v in ipairs(val) do
82-
table.insert(res, encode(v, stack))
83+
for i=1,length do
84+
table.insert(res, encode(val[i], stack))
8385
end
8486
stack[val] = nil
8587
return "[" .. table.concat(res, ",") .. "]"
8688

8789
else
8890
-- Treat as an object
8991
for k, v in pairs(val) do
92+
--[[
9093
if type(k) ~= "string" then
9194
error("invalid table: mixed or invalid key types")
9295
end
96+
]]
9397
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
9498
end
9599
stack[val] = nil
@@ -108,7 +112,7 @@ local function encode_number(val)
108112
if val ~= val or val <= -math.huge or val >= math.huge then
109113
error("unexpected number value '" .. tostring(val) .. "'")
110114
end
111-
return string.format("%.14g", val)
115+
return tostring(val)
112116
end
113117

114118

0 commit comments

Comments
 (0)