pull/28/merge
Milind Gupta 2023-11-27 20:38:15 -08:00 committed by GitHub
commit 3489d1edcd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 250 additions and 240 deletions

View File

@ -22,7 +22,10 @@
-- SOFTWARE.
--
local json = { _version = "0.1.2" }
local json = {
_version = "0.1.2" ,
SPARSELIMIT = 100, -- To set the limit on how long sparse arrays can be
}
-------------------------------------------------------------------------------
-- Encode
@ -64,32 +67,39 @@ 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
local nLen = 0
local count = 0
for k,v in pairs(val) do
if (type(k) ~= "number" or k<=0 or k%1 ~= 0) and not (k == "n" and type(v) == "number") then
array = nil
break -- Treat as object
else
if k > length then
length = k
end
if k == "n" and type(v) == "number" then
nLen = v
end
count = count + 1
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")
if nLen > length then
length = nLen
end
if array and not (length > SPARSELIMIT and count ~= length) then -- Check Array detected but sparse > 100 length then treat as object
-- 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