fix(best_effor_json): make tuple list check more efficient

This commit is contained in:
Kjell Winblad 2024-05-16 15:40:38 +02:00
parent 413ad60bdb
commit b7c2f4a6d7
1 changed files with 8 additions and 9 deletions

View File

@ -219,9 +219,7 @@ best_effort_unicode(Input, Config) ->
best_effort_json_obj(List, Config) when is_list(List) -> best_effort_json_obj(List, Config) when is_list(List) ->
try try
%% We should only do this if there are no duplicated keys json_obj(convert_tuple_list_to_map(List), Config)
check_no_dup_tuple_list(List),
json_obj(maps:from_list(List), Config)
catch catch
_:_ -> _:_ ->
[json(I, Config) || I <- List] [json(I, Config) || I <- List]
@ -234,14 +232,15 @@ best_effort_json_obj(Map, Config) ->
do_format_msg("~p", [Map], Config) do_format_msg("~p", [Map], Config)
end. end.
check_no_dup_tuple_list(List) -> %% This function will throw if the list do not only contain tuples or if there
%% are duplicate keys.
convert_tuple_list_to_map(List) ->
%% Crash if this is not a tuple list %% Crash if this is not a tuple list
lists:foreach(fun({_, _}) -> ok end, List), CandidateMap = maps:from_list(List),
Items = [K || {K, _} <- List],
NumberOfItems = length(Items),
%% Crash if there are duplicates %% Crash if there are duplicates
NumberOfItems = maps:size(maps:from_keys(Items, true)), NumberOfItems = length(List),
ok. NumberOfItems = maps:size(CandidateMap),
CandidateMap.
json(A, _) when is_atom(A) -> A; json(A, _) when is_atom(A) -> A;
json(I, _) when is_integer(I) -> I; json(I, _) when is_integer(I) -> I;