Browse Source

Raise an error if a decode target JSON is followed by extra garbage chars.

Takeru Ohta 3 years ago
parent
commit
4c24e00676
2 changed files with 24 additions and 1 deletions
  1. 19 1
      src/jsone.erl
  2. 5 0
      test/jsone_decode_tests.erl

+ 19 - 1
src/jsone.erl

@@ -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 ->
@@ -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 - 0
test/jsone_decode_tests.erl

@@ -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",