2121
2222local cjson = require (" cjson.safe" )
2323local json_encode = cjson .encode
24+ local json_decode = cjson .decode
25+ local cjson_null = cjson .null
2426local clear_tab = require (" table.clear" )
2527local ngx = ngx
2628local tostring = tostring
@@ -34,14 +36,47 @@ cjson.decode_array_with_array_mt(true)
3436local _M = {
3537 version = 0.1 ,
3638 array_mt = cjson .array_mt ,
37- decode = cjson . decode ,
39+ null = cjson_null ,
3840 -- This method produces the same encoded string when the input is not changed.
3941 -- Different calls with cjson.encode will produce different string because
4042 -- it doesn't maintain the object key order.
4143 stably_encode = require (" dkjson" ).encode
4244}
4345
4446
47+ local function strip_nulls (t )
48+ for k , v in pairs (t ) do
49+ if v == cjson_null then
50+ t [k ] = nil
51+ elseif type (v ) == " table" then
52+ strip_nulls (v )
53+ end
54+ end
55+ return t
56+ end
57+ _M .strip_nulls = strip_nulls
58+
59+
60+ --- Decode a JSON string.
61+ -- @tparam string str The JSON string to decode.
62+ -- @tparam [opt] table opts Options table.
63+ -- null_as_nil: if true, recursively replace cjson.null with nil.
64+ -- @return The decoded Lua value, or nil on error.
65+ -- @return Error string on failure.
66+ function _M .decode (str , opts )
67+ local obj , err = json_decode (str )
68+ if obj and opts and opts .null_as_nil then
69+ if obj == cjson_null then
70+ return nil , err
71+ end
72+ if type (obj ) == " table" then
73+ strip_nulls (obj )
74+ end
75+ end
76+ return obj , err
77+ end
78+
79+
4580local function serialise_obj (data )
4681 if type (data ) == " function" or type (data ) == " userdata"
4782 or type (data ) == " cdata"
0 commit comments