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:
adjuvant 2023-08-20 21:32:52 +02:00 committed by XeroOl
parent e7c642e12a
commit 7c1bbc8c2b
3 changed files with 22 additions and 3 deletions

View File

@ -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 * 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 in type conversion or other magic: sparse arrays, tables with mixed key types
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 are converted to the special value `json.null`
are therefore lost upon decoding
* *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

View File

@ -24,6 +24,9 @@
local json = { _version = "0.1.2" } local json = { _version = "0.1.2" }
-- unique placeholder for "null"
json.null = { _ = "nil" }
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- Encode -- Encode
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
@ -122,6 +125,10 @@ local type_func_map = {
encode = function(val, stack) encode = function(val, stack)
if val == json.null then
return encode_nil(val)
end
local t = type(val) local t = type(val)
local f = type_func_map[t] local f = type_func_map[t]
if f then if f then
@ -158,7 +165,7 @@ local literals = create_set("true", "false", "null")
local literal_map = { local literal_map = {
[ "true" ] = true, [ "true" ] = true,
[ "false" ] = false, [ "false" ] = false,
[ "null" ] = nil, [ "null" ] = json.null,
} }

View File

@ -243,3 +243,16 @@ test("encode escape", function()
assert( res == v, fmt("'%s' was not escaped properly", k) ) assert( res == v, fmt("'%s' was not escaped properly", k) )
end end
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)