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 May 5, 2023
1 parent 3b81786 commit bde032c
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions rockspecs/pegasus-dev-1.rockspec
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ build = {
modules = {
['pegasus.init'] = "src/pegasus/init.lua",
['pegasus.handler'] = 'src/pegasus/handler.lua',
['pegasus.json'] = 'src/pegasus/json.lua',
['pegasus.request'] = 'src/pegasus/request.lua',
['pegasus.response'] = 'src/pegasus/response.lua',
['pegasus.compress'] = 'src/pegasus/compress.lua',
Expand Down
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 bde032c

Please sign in to comment.