json.lua: Allow encoding null values
A similar proposal was already rejected upstream: https://github.com/rxi/json.lua/pull/6
This commit is contained in:
parent
e7c642e12a
commit
7c1bbc8c2b
@ -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
|
||||
|
||||
|
||||
@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user