Improved indentation by using tab. Added module variable SPARSELIMIT to control the length threshold of sparse arrays. Some bug fixes and improvements as suggested by @appgurueu

pull/28/head
Milind Gupta 2023-11-27 20:38:05 -08:00
parent 75127d2c7d
commit 0e6634a54e
1 changed files with 210 additions and 212 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
@ -70,7 +73,7 @@ local function encode_table(val, stack)
local nLen = 0
local count = 0
for k,v in pairs(val) do
if (type(k) ~= "number" or k<=0) and not (k == "n" and type(v) == "number") then
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
@ -87,7 +90,7 @@ local function encode_table(val, stack)
if nLen > length then
length = nLen
end
if array and not (length > 100 and count ~= length) then -- Check Array detected but sparse > 100 length then treat as object
if array and not (length > SPARSELIMIT and count ~= length) then -- Check Array detected but sparse > 100 length then treat as object
-- Encode
for i=1,length do
table.insert(res, encode(val[i], stack))
@ -97,11 +100,6 @@ local function encode_table(val, stack)
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
@ -120,7 +118,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 tostring(val)
return string.format("%.14g",val)
end