JSON: Add encode / decode shortcut
[project/luci.git] / libs / json / luasrc / json.lua
index 26b540428a31c79fa744b93cf6f6c66f9201e02d..5b0928590f9f5a661cbd06e024baa0ed257ac629 100644 (file)
@@ -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()