Adds support for encoding null values

pull/6/head
jdeseno 2017-12-03 18:05:35 -08:00
parent e1dbe93f7c
commit 881c36236a
3 changed files with 21 additions and 1 deletions

View File

@ -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

View File

@ -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

View File

@ -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)