Skip to content

Commit eb6e343

Browse files
committed
Added checking and tests for trailing garbage when decoding
1 parent 19cc024 commit eb6e343

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

json.lua

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,12 @@ function json.decode(str)
388388
if type(str) ~= "string" then
389389
error("expected argument of type string, got " .. type(str))
390390
end
391-
return ( parse(str, next_char(str, 1, space_chars, true)) )
391+
local res, idx = parse(str, next_char(str, 1, space_chars, true))
392+
idx = next_char(str, idx, space_chars, true)
393+
if idx <= #str then
394+
decode_error(str, idx, "trailing garbage")
395+
end
396+
return res
392397
end
393398

394399

test/test.lua

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ end)
5757

5858
test("literals", function()
5959
assert( json.decode("true") == true )
60-
assert( json.encode(true) == "true" )
60+
assert( json.encode(true) == "true" )
6161
assert( json.decode("false") == false )
6262
assert( json.encode(false) == "false" )
6363
assert( json.decode("null") == nil )
@@ -125,6 +125,8 @@ test("decode invalid", function()
125125
'{]',
126126
'[}',
127127
'"a',
128+
'10 xx',
129+
'{}123'
128130
}
129131
for i, v in ipairs(t) do
130132
local status = pcall(json.decode, v)
@@ -234,5 +236,3 @@ test("encode escape", function()
234236
assert( res == v, fmt("'%s' was not escaped properly", k) )
235237
end
236238
end)
237-
238-

0 commit comments

Comments
 (0)