Skip to content

Commit

Permalink
feat(json): add a json library
Browse files Browse the repository at this point in the history
This is a wrapper around any of the following Lua modules; 'lua-cjson',
'dkjson', or 'rapidjson'.
  • Loading branch information
Tieske committed Mar 3, 2023
1 parent 303abcf commit 3a3d433
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/pegasus/json.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
-- Wrapper library that supports multiple JSON libraries
local found, jsonlib

found, jsonlib = pcall(require, "cjson.safe") -- lua-cjson
if found then
return setmetatable({
-- decode is available
-- encode is available
-- null is available
available = true,
makeArray= function(t)
assert(type(t) == "table", "expected a table")
return setmetatable(t, jsonlib.array_mt)
end,
}, { __index = jsonlib })
end


found, jsonlib = pcall(require, "dkjson") -- dkjson
if found then
local array_mt = { __jsontype='array'}
return setmetatable({
-- decode is available
-- encode is available
-- null is available
available = true,
makeArray= function(t)
assert(type(t) == "table", "expected a table")
return setmetatable(t, array_mt)
end,
}, { __index = jsonlib })
end


found, jsonlib = pcall(require, "rapidjson") -- rapidjson
if found then
local array_mt = { __jsontype='array'}
return setmetatable({
decode = function(value)
return jsonlib.decode(value, 1, jsonlib.null)
end,
-- encode is available
-- null is available
available = true,
makeArray= function(t)
assert(type(t) == "table", "expected a table")
return setmetatable(t, array_mt)
end,
}, { __index = jsonlib })
end


local err = function()
return nil, "no json library available, install 'lua-cjson', 'dkjson', or 'rapidjson'"
end

return {
available = false,
encode = err,
decode = err,
makeArray = err,
}

0 comments on commit 3a3d433

Please sign in to comment.