fix: add is_json

This commit is contained in:
Stefan Strigler 2023-04-13 15:49:12 +02:00
parent 062ce5f819
commit 19981757ae
3 changed files with 16 additions and 4 deletions

View File

@ -46,11 +46,15 @@
]}
).
-type encode_options() :: emqx_utils_json:encode_options().
-type decode_options() :: emqx_utils_json:decode_options().
-export([is_json/1]).
-compile({inline, [is_json/1]}).
-type encode_options() :: jiffy:encode_options().
-type decode_options() :: jiffy:decode_options().
-type json_text() :: iolist() | binary().
-type json_term() :: emqx_utils_json:jiffy_decode_result().
-type json_term() :: jiffy:jiffy_decode_result().
-export_type([json_text/0, json_term/0]).
-export_type([decode_options/0, encode_options/0]).
@ -79,7 +83,7 @@ safe_encode(Term, Opts) ->
end.
-spec decode(json_text()) -> json_term().
decode(Json) -> decode(Json, []).
decode(Json) -> decode(Json, [return_maps]).
-spec decode(json_text(), decode_options()) -> json_term().
decode(Json, Opts) ->
@ -100,6 +104,10 @@ safe_decode(Json, Opts) ->
{error, Reason}
end.
-spec is_json(json_text()) -> boolean().
is_json(Json) ->
element(1, safe_decode(Json)) =:= ok.
%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------

View File

@ -136,3 +136,7 @@ safe_encode_decode(Term) ->
{ok, {NTerm}} -> NTerm;
{ok, NTerm} -> NTerm
end.
t_is_json(_) ->
?assert(emqx_utils_json:is_json(<<"{}">>)),
?assert(not emqx_utils_json:is_json(<<"foo">>)).