diff --git a/README.md b/README.md index 5f95beb..c2a80c1 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ json.decode('[1,2,3,{"x":10}]') -- Returns { 1, 2, 3, { x = 10 } } 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 +* Alternatively `null` values may be encoded using `json.null` instead of `nil` * *Pretty* encoding is not supported, `json.encode()` only encodes to a compact format diff --git a/json.lua b/json.lua index dda6193..ebfa6c3 100644 --- a/json.lua +++ b/json.lua @@ -9,6 +9,15 @@ local json = { _version = "0.1.0" } +------------------------------------------------------------------------------- +-- Null encoding support +------------------------------------------------------------------------------- +local _null_type = "null" +local _null_mt = { + __index={ __type = _null_type } +} +json.null = setmetatable({}, _null_mt) + ------------------------------------------------------------------------------- -- Encode ------------------------------------------------------------------------------- @@ -42,6 +51,10 @@ end local function encode_table(val, stack) + if val.__type == _null_type then + return encode_nil(val) + end + local res = {} stack = stack or {} @@ -376,5 +389,4 @@ function json.decode(str) return ( parse(str, next_char(str, 1, space_chars, true)) ) end - return json diff --git a/test/test.lua b/test/test.lua index 88138d0..b99c34e 100644 --- a/test/test.lua +++ b/test/test.lua @@ -235,4 +235,11 @@ test("encode escape", function() end end) +test("encode null", function() + assert( json.encode{foo=json.null} == [[{"foo":null}]], + "json.null was not preserved" ) + + assert( json.encode({foo=nil}) == "[]", + "nil was not lost" ) +end)