fix(json): allow objects with empty keys #25564

Problem:
Empty string is a valid JSON key, but json_decode() treats an object
with empty key as ":help msgpack-special-dict". #20757

    :echo json_decode('{"": "1"}')
    {'_TYPE': [], '_VAL': [['', '1']]}

Note: vim returns `{'': '1'}`.

Solution:
Allow empty string as an object key.

Note that we still (currently) disallow empty keys in object_to_vim() (since 7c01d5ff92):
f64e4b43e1/src/nvim/api/private/converter.c (L333-L334)

Fix #20757

Co-authored-by: Justin M. Keyes <justinkz@gmail.com>
This commit is contained in:
Emanuel
2023-12-06 16:56:04 +01:00
committed by GitHub
parent c84af395e8
commit e057b38e70
6 changed files with 17 additions and 28 deletions

View File

@@ -467,19 +467,18 @@ describe('json_decode() function', function()
'[1, {"d": {"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}}]')
sp_decode_eq({1, {a={}, d={_TYPE='map', _VAL={{'b', 3}, {'a', 1}, {'c', 4}, {'a', 2}, {'c', 4}}}}},
'[1, {"a": [], "d": {"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}}]')
end)
it('parses dictionaries with empty keys to special maps', function()
sp_decode_eq({_TYPE='map', _VAL={{'', 4}}},
'{"": 4}')
sp_decode_eq({_TYPE='map', _VAL={{'b', 3}, {'a', 1}, {'c', 4}, {'d', 2}, {'', 4}}},
'{"b": 3, "a": 1, "c": 4, "d": 2, "": 4}')
sp_decode_eq({_TYPE='map', _VAL={{'', 3}, {'a', 1}, {'c', 4}, {'d', 2}, {'', 4}}},
'{"": 3, "a": 1, "c": 4, "d": 2, "": 4}')
sp_decode_eq({{_TYPE='map', _VAL={{'', 3}, {'a', 1}, {'c', 4}, {'d', 2}, {'', 4}}}},
'[{"": 3, "a": 1, "c": 4, "d": 2, "": 4}]')
end)
it('parses dictionaries with empty keys', function()
eq({[""] = 4}, funcs.json_decode('{"": 4}'))
eq({b = 3, a = 1, c = 4, d = 2, [""] = 4},
funcs.json_decode('{"b": 3, "a": 1, "c": 4, "d": 2, "": 4}'))
end)
it('parses dictionaries with keys with NUL bytes to special maps', function()
sp_decode_eq({_TYPE='map', _VAL={{{_TYPE='string', _VAL={'a\n', 'b'}}, 4}}},
'{"a\\u0000\\nb": 4}')
@@ -577,6 +576,8 @@ describe('json_encode() function', function()
eq('{}', eval('json_encode({})'))
eq('{"d": []}', funcs.json_encode({d={}}))
eq('{"d": [], "e": []}', funcs.json_encode({d={}, e={}}))
-- Empty keys not allowed (yet?) in object_to_vim() (since 7c01d5ff9286). #25564
-- eq('{"": []}', funcs.json_encode({['']={}}))
end)
it('cannot dump generic mapping with generic mapping keys and values',