From 70556ccea5b33ffcbb62eb1dc7288b287de28438 Mon Sep 17 00:00:00 2001 From: rxi Date: Sun, 30 Aug 2015 19:08:50 +0100 Subject: [PATCH] Added checking for sparseness and mixed key types when encoding array --- README.md | 2 +- json.lua | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 03482b4..f814d0a 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/json.lua b/json.lua index f04724b..205dfb4 100644 --- a/json.lua +++ b/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