mirror of https://github.com/rxi/json.lua.git
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
parent
75127d2c7d
commit
0e6634a54e
16
json.lua
16
json.lua
|
@ -22,7 +22,10 @@
|
||||||
-- SOFTWARE.
|
-- 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
|
-- Encode
|
||||||
|
@ -70,7 +73,7 @@ local function encode_table(val, stack)
|
||||||
local nLen = 0
|
local nLen = 0
|
||||||
local count = 0
|
local count = 0
|
||||||
for k,v in pairs(val) do
|
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
|
array = nil
|
||||||
break -- Treat as object
|
break -- Treat as object
|
||||||
else
|
else
|
||||||
|
@ -87,7 +90,7 @@ local function encode_table(val, stack)
|
||||||
if nLen > length then
|
if nLen > length then
|
||||||
length = nLen
|
length = nLen
|
||||||
end
|
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
|
-- Encode
|
||||||
for i=1,length do
|
for i=1,length do
|
||||||
table.insert(res, encode(val[i], stack))
|
table.insert(res, encode(val[i], stack))
|
||||||
|
@ -97,11 +100,6 @@ local function encode_table(val, stack)
|
||||||
else
|
else
|
||||||
-- Treat as an object
|
-- Treat as an object
|
||||||
for k, v in pairs(val) do
|
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))
|
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
|
||||||
end
|
end
|
||||||
stack[val] = nil
|
stack[val] = nil
|
||||||
|
@ -120,7 +118,7 @@ local function encode_number(val)
|
||||||
if val ~= val or val <= -math.huge or val >= math.huge then
|
if val ~= val or val <= -math.huge or val >= math.huge then
|
||||||
error("unexpected number value '" .. tostring(val) .. "'")
|
error("unexpected number value '" .. tostring(val) .. "'")
|
||||||
end
|
end
|
||||||
return tostring(val)
|
return string.format("%.14g",val)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue