mirror of https://github.com/rxi/json.lua.git
Added checking for sparseness and mixed key types when encoding array
parent
3845cef229
commit
70556ccea5
|
@ -6,7 +6,7 @@ A lightweight JSON library for Lua
|
|||
* Implemented in pure Lua: works with 5.1, 5.2, 5.3 and JIT
|
||||
* Fast: generally outperforms other pure Lua JSON implementations
|
||||
([benchmark scripts](bench/))
|
||||
* Tiny: around 280sloc, 8.5kb
|
||||
* Tiny: around 290sloc, 9kb
|
||||
* Proper error messages, *eg:* `expected '}' or ',' at line 203 col 30`
|
||||
|
||||
|
||||
|
|
16
json.lua
16
json.lua
|
@ -51,7 +51,19 @@ local function encode_table(val, stack)
|
|||
stack[val] = true
|
||||
|
||||
if val[1] ~= nil then
|
||||
-- Treat as an array
|
||||
-- Treat as array -- check keys are valid and it is not sparse
|
||||
local n = 0
|
||||
for k in pairs(val) do
|
||||
local t = type(k)
|
||||
if t ~= "number" then
|
||||
error("unexpected key of type '" .. t .. "' in array")
|
||||
end
|
||||
n = n + 1
|
||||
end
|
||||
if n ~= #val then
|
||||
error("unexpected sparse array")
|
||||
end
|
||||
-- Encode
|
||||
for i, v in ipairs(val) do
|
||||
table.insert(res, encode(v, stack))
|
||||
end
|
||||
|
@ -63,7 +75,7 @@ local function encode_table(val, stack)
|
|||
for k, v in pairs(val) do
|
||||
local t = type(k)
|
||||
if t ~= "string" then
|
||||
error("expected key of type 'string', got '" .. t .. "'")
|
||||
error("unexpected key of type '" .. t .. "' in object")
|
||||
end
|
||||
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue