diff --git a/src/json/README.md b/src/json/README.md index 96b9b66..83a7a93 100644 --- a/src/json/README.md +++ b/src/json/README.md @@ -34,8 +34,7 @@ json.decode('[1,2,3,{"x":10}]') -- Returns { 1, 2, 3, { x = 10 } } * Trying to encode values which are unrepresentable in JSON will never result in type conversion or other magic: sparse arrays, tables with mixed key types or invalid numbers (NaN, -inf, inf) will raise an error -* `null` values contained within an array or object are converted to `nil` and - are therefore lost upon decoding +* `null` values are converted to the special value `json.null` * *Pretty* encoding is not supported, `json.encode()` only encodes to a compact format diff --git a/src/json/json.lua b/src/json/json.lua index 711ef78..3929ae2 100644 --- a/src/json/json.lua +++ b/src/json/json.lua @@ -24,6 +24,9 @@ local json = { _version = "0.1.2" } +-- unique placeholder for "null" +json.null = { _ = "nil" } + ------------------------------------------------------------------------------- -- Encode ------------------------------------------------------------------------------- @@ -122,6 +125,10 @@ local type_func_map = { encode = function(val, stack) + if val == json.null then + return encode_nil(val) + end + local t = type(val) local f = type_func_map[t] if f then @@ -158,7 +165,7 @@ local literals = create_set("true", "false", "null") local literal_map = { [ "true" ] = true, [ "false" ] = false, - [ "null" ] = nil, + [ "null" ] = json.null, } diff --git a/src/json/test/test.lua b/src/json/test/test.lua index 74470b2..ceba87e 100644 --- a/src/json/test/test.lua +++ b/src/json/test/test.lua @@ -243,3 +243,16 @@ test("encode escape", function() assert( res == v, fmt("'%s' was not escaped properly", k) ) end end) + +test("encode null", function() + local t = { + a = "foo", + b = json.null, + c = 42, + } + local res = json.decode( json.encode(t) ) + for k, v in pairs(t) do + assert( equal( v, res[k] ) ) + end + assert( equal( json.null, res.b ) ) +end)