Skip to content

Commit

Permalink
Merge pull request #69 from sile/check-garbage-chars
Browse files Browse the repository at this point in the history
Raise an error if a decode target JSON is followed by extra garbage chars.
  • Loading branch information
sile authored Nov 15, 2021
2 parents 5b8a858 + 4c24e00 commit 31e9f0e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/jsone.erl
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,8 @@ decode(Json) ->
-spec decode(binary(), [decode_option()]) -> json_value().
decode(Json, Options) ->
try
{ok, Value, _} = try_decode(Json, Options),
{ok, Value, Remainings} = try_decode(Json, Options),
check_decode_remainings(Remainings),
Value
catch
error:{badmatch, {error, {Reason, [StackItem]}}} ?CAPTURE_STACKTRACE ->
Expand Down Expand Up @@ -441,3 +442,20 @@ term_to_json_string(X) ->
-spec ip_address_to_json_string(inet:ip_address()|any()) -> {ok, json_string()} | error.
ip_address_to_json_string(X) ->
jsone_inet:ip_address_to_json_string(X).

%%--------------------------------------------------------------------------------
%% Internal Functions
%%--------------------------------------------------------------------------------
-spec check_decode_remainings(binary()) -> ok.
check_decode_remainings(<<>>) ->
ok;
check_decode_remainings(<<$ , Bin/binary>>) ->
check_decode_remainings(Bin);
check_decode_remainings(<<$\t, Bin/binary>>) ->
check_decode_remainings(Bin);
check_decode_remainings(<<$\r, Bin/binary>>) ->
check_decode_remainings(Bin);
check_decode_remainings(<<$\n, Bin/binary>>) ->
check_decode_remainings(Bin);
check_decode_remainings(<<Bin/binary>>) ->
erlang:error(badarg, [Bin]).
5 changes: 5 additions & 0 deletions test/jsone_decode_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,11 @@ decode_test_() ->
[{Atom, <<"ok">>}] = jsone:decode(<<"{\"", Value/binary, "\":\"ok\"}">>, KeyOpt(atom)),
?assertEqual(Value, atom_to_binary(Atom, latin1))
end},
{"garbage remainings chars",
fun () ->
?assertError(badarg, jsone:decode(<<"1@">>)),
?assertEqual(1, jsone:decode(<<"1 \n\t\r ">>)) % Whitespaces are OK
end},

%% Others
{"compound data",
Expand Down

0 comments on commit 31e9f0e

Please sign in to comment.