mirror of https://github.com/rxi/json.lua.git
Merge 0e6634a54e
into dbf4b2dd2e
commit
3489d1edcd
46
json.lua
46
json.lua
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue