diff options
author | Steven Barth <steven@midlink.org> | 2009-11-13 18:25:59 +0000 |
---|---|---|
committer | Steven Barth <steven@midlink.org> | 2009-11-13 18:25:59 +0000 |
commit | 43820b99ecac96b1f5c3abe44eb446cdea5d41b4 (patch) | |
tree | 6a5b54c18fdbb39c6d61d9db2baea3391bdcde04 /libs/json/luasrc/json.lua | |
parent | 7da7ada00b6e8849e9a64bfe825b25d119879c74 (diff) |
JSON: Add encode / decode shortcut
Diffstat (limited to 'libs/json/luasrc/json.lua')
-rw-r--r-- | libs/json/luasrc/json.lua | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/libs/json/luasrc/json.lua b/libs/json/luasrc/json.lua index 26b540428..5b0928590 100644 --- a/libs/json/luasrc/json.lua +++ b/libs/json/luasrc/json.lua @@ -52,6 +52,7 @@ local type = type local pairs = pairs local ipairs = ipairs local next = next +local pcall = pcall local getmetatable = getmetatable @@ -59,6 +60,33 @@ local getmetatable = getmetatable -- @cstyle instance module "luci.json" + +--- Directly decode a JSON string +-- @param json JSON-String +-- @return Lua object +function decode(json, ...) + local a = ActiveDecoder(function() return nil end, ...) + a.chunk = json + local s, obj = pcall(a.get, a) + return s and obj or nil +end + + +--- Direcly encode a Lua object into a JSON string. +-- @param obj Lua Object +-- @return JSON string +function encode(obj, ...) + local out = {} + local e = Encoder(obj, 1, ...):source() + local chnk, err + repeat + chnk, err = e() + out[#out+1] = chnk + until chnk + return not err and table.concat(out) or nil +end + + --- Null replacement function -- @return null function null() |