Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add json format functions for key-value lists #8889

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion lib/stdlib/src/json.erl
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ standards. The decoder is tested using [JSONTestSuite](https://github.com/nst/JS

-export([
format/1, format/2, format/3,
format_value/3
format_value/3,
format_key_value_list/3,
format_key_value_list_checked/3
]).
-export_type([formatter/0]).

Expand Down Expand Up @@ -694,6 +696,14 @@ format_tail([Head|Tail], Enc, State, IndentAll, IndentRow) ->
format_tail([], _, _, _, _) ->
[].

-doc """
Format function for lists of key-value pairs as JSON objects.

Accepts lists with atom, binary, integer, or float keys.
""".
-doc(#{since => <<"OTP 27.2">>}).

-spec format_key_value_list([{term(), term()}], Encode::formatter(), State::map()) -> iodata().
format_key_value_list(KVList, UserEnc, #{level := Level} = State) ->
{_,Indent} = indent(State),
NextState = State#{level := Level+1},
Expand All @@ -706,6 +716,48 @@ format_key_value_list(KVList, UserEnc, #{level := Level} = State) ->
end,
format_object([Entry(Key,Value) || {Key, Value} <- KVList], Indent).

isvilen marked this conversation as resolved.
Show resolved Hide resolved
isvilen marked this conversation as resolved.
Show resolved Hide resolved
-doc """
Format function for lists of key-value pairs as JSON objects.

Accepts lists with atom, binary, integer, or float keys.
Verifies that no duplicate keys will be produced in the
resulting JSON object.

## Errors

Raises `error({duplicate_key, Key})` if there are duplicates.
""".
-doc(#{since => <<"OTP 27.2">>}).

-spec format_key_value_list_checked([{term(), term()}], Encoder::formatter(), State::map()) -> iodata().
format_key_value_list_checked(KVList, UserEnc, State) when is_function(UserEnc, 3) ->
{_,Indent} = indent(State),
format_object(do_format_checked(KVList, UserEnc, State), Indent).

do_format_checked([], _, _) ->
[];

do_format_checked(KVList, UserEnc, #{level := Level} = State) ->
NextState = State#{level := Level + 1},
{KISize, KeyIndent} = indent(NextState),
EncKeyFun = fun(KeyVal, _Fun) -> UserEnc(KeyVal, UserEnc, NextState) end,
EncListFun =
fun({Key, Value}, {Acc, Visited0}) ->
EncKey = iolist_to_binary(key(Key, EncKeyFun)),
case is_map_key(EncKey, Visited0) of
true ->
error({duplicate_key, Key});
false ->
Visited1 = Visited0#{EncKey => true},
ValState = NextState#{col := KISize + 2 + erlang:iolist_size(EncKey)},
EncEntry = [$, , KeyIndent, EncKey, ": "
| UserEnc(Value, UserEnc, ValState)],
{[EncEntry | Acc], Visited1}
end
end,
{EncKVList, _} = lists:foldl(EncListFun, {[], #{}}, KVList),
lists:reverse(EncKVList).

isvilen marked this conversation as resolved.
Show resolved Hide resolved
format_object([], _) -> <<"{}">>;
format_object([[_Comma,KeyIndent|Entry]], Indent) ->
[_Key,_Colon|Value] = Entry,
Expand Down
33 changes: 33 additions & 0 deletions lib/stdlib/test/json_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
test_encode_proplist/1,
test_encode_escape_all/1,
test_format_list/1,
test_format_proplist/1,
test_format_map/1,
test_format_fun/1,
test_decode_atoms/1,
Expand Down Expand Up @@ -91,6 +92,7 @@ groups() ->
]},
{format, [parallel], [
test_format_list,
test_format_proplist,
test_format_map,
test_format_fun
]},
Expand Down Expand Up @@ -367,6 +369,37 @@ test_format_list(_Config) ->
?assertEqual(ListString, format([~"foo", ~"bar", ~"baz"], #{indent => 3})),
ok.

test_format_proplist(_Config) ->
Formatter = fun({kvlist, KVList}, Fun, State) ->
json:format_key_value_list(KVList, Fun, State);
({kvlist_checked, KVList}, Fun, State) ->
json:format_key_value_list_checked(KVList, Fun, State);
(Other, Fun, State) ->
json:format_value(Other, Fun, State)
end,

?assertEqual(~"""
{
"a": 1,
"b": "str"
}

""", format({kvlist, [{a, 1}, {b, ~"str"}]}, Formatter)),

?assertEqual(~"""
{
"a": 1,
"b": "str"
}

""", format({kvlist_checked, [{a, 1}, {b, ~"str"}]}, Formatter)),


?assertError({duplicate_key, a},
format({kvlist_checked, [{a, 1}, {b, ~"str"}, {a, 2}]}, Formatter)),

ok.

isvilen marked this conversation as resolved.
Show resolved Hide resolved
test_format_map(_Config) ->
?assertEqual(~'{}\n', format(#{})),
?assertEqual(~'{ "key": "val" }\n', format(#{key => val})),
Expand Down
Loading