mirror of https://github.com/rxi/json.lua.git
Adds support for encoding null values
parent
e1dbe93f7c
commit
881c36236a
|
@ -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
|
or invalid numbers (NaN, -inf, inf) will raise an error
|
||||||
* `null` values contained within an array or object are converted to `nil` and
|
* `null` values contained within an array or object are converted to `nil` and
|
||||||
are therefore lost upon decoding
|
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
|
* *Pretty* encoding is not supported, `json.encode()` only encodes to a compact
|
||||||
format
|
format
|
||||||
|
|
||||||
|
|
14
json.lua
14
json.lua
|
@ -9,6 +9,15 @@
|
||||||
|
|
||||||
local json = { _version = "0.1.0" }
|
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
|
-- Encode
|
||||||
-------------------------------------------------------------------------------
|
-------------------------------------------------------------------------------
|
||||||
|
@ -42,6 +51,10 @@ end
|
||||||
|
|
||||||
|
|
||||||
local function encode_table(val, stack)
|
local function encode_table(val, stack)
|
||||||
|
if val.__type == _null_type then
|
||||||
|
return encode_nil(val)
|
||||||
|
end
|
||||||
|
|
||||||
local res = {}
|
local res = {}
|
||||||
stack = stack or {}
|
stack = stack or {}
|
||||||
|
|
||||||
|
@ -376,5 +389,4 @@ function json.decode(str)
|
||||||
return ( parse(str, next_char(str, 1, space_chars, true)) )
|
return ( parse(str, next_char(str, 1, space_chars, true)) )
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
return json
|
return json
|
||||||
|
|
|
@ -235,4 +235,11 @@ test("encode escape", function()
|
||||||
end
|
end
|
||||||
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)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue