Merge pull request #6 from alexandro-rezakhani/alexandro-rezakhani-patch-1

Update json.lua
pull/44/head
alexandro-rezakhani 2022-11-20 00:28:22 -05:00 committed by GitHub
commit cd2b736e8c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 42 additions and 38 deletions

View File

@ -55,6 +55,7 @@ local function encode_nil(val)
return "null" return "null"
end end
local json_object_tag = {}
local function encode_table(val, stack) local function encode_table(val, stack)
local res = {} local res = {}
@ -64,6 +65,8 @@ local function encode_table(val, stack)
if stack[val] then error("circular reference") end if stack[val] then error("circular reference") end
stack[val] = true stack[val] = true
if getmetatable(val) ~= json_object_tag and (rawget(val, 1) ~= nil or next(val) == nil) then
-- Check whether to treat as a array or object -- Check whether to treat as a array or object
local array = true local array = true
local length = 0 local length = 0
@ -81,7 +84,6 @@ local function encode_table(val, stack)
end end
end end
end end
if array then if array then
if nLen > length then if nLen > length then
length = nLen length = nLen
@ -92,7 +94,6 @@ local function encode_table(val, stack)
end end
stack[val] = nil stack[val] = nil
return "[" .. table.concat(res, ",") .. "]" return "[" .. table.concat(res, ",") .. "]"
else else
-- Treat as an object -- Treat as an object
for k, v in pairs(val) do for k, v in pairs(val) do
@ -101,11 +102,14 @@ local function encode_table(val, stack)
error("invalid table: mixed or invalid key types") error("invalid table: mixed or invalid key types")
end end
]] ]]
if k ~= "_" then
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack)) table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end end
end
stack[val] = nil stack[val] = nil
return "{" .. table.concat(res, ",") .. "}" return "{" .. table.concat(res, ",") .. "}"
end end
end
end end