-
Notifications
You must be signed in to change notification settings - Fork 3.4k
JSON encode supports encoding keyword lists to objects #14431
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
Conversation
@@ -304,6 +304,8 @@ encode_list(List, Encode) when is_list(List) -> | |||
|
|||
do_encode_list([], _Encode) -> | |||
<<"[]">>; | |||
do_encode_list([{Key, _Value} | _Rest] = List, Encode) when is_atom(Key) -> | |||
encode_key_value_list_checked(List, Encode); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
One edge case that could be done either way is encoding an invalid keyword list list such as [k1: "a", k2: "b", "BAD"]
, which isn't valid syntax in that form, but could still be expressed as [{:k1, "a", {:k2, "b"}, "BAD"]
, or duplicate keys like [k1: "a", k2: "b", k1: "c"]
.
This is using encode_key_value_list_checked/2
, which will correctly raise an error on bad input: if there is a dup key, or any element that doesn't match {Key, Value}
in the list, but will have a performance overhead.
Alternative is to just use encode_key_value_list/2
, which is faster, but will allow duplicate keys to be encoded, and will just skip invalid list items.
We must not change the |
In any case, thank you for the PR! |
I would be against such a change since, as you said, it's just a heuristic and the list of pairs, might not actually be pairs after all - this can end up with quite confusing errors. def encode!(value) do
JSON.encode!(value, fn
[{_, _} | _] = kv, encode -> :json.encode_key_value_list(kv, encode);
other, encode -> JSON.protocol_encode(other, encode)
end)
end |
Indeed, and there's also the issue of the empty list possibly meaning an empty object, but being translated as a list. Perhaps a nice way to achieve this without ambiguity in user land could be to define a custom |
That's what we had in |
Ok, given the feedback above, we won't move forward with this. Thanks! :) |
Allow keyword lists with atom keys to be encoding with
JSON
moduleCurrent:
With change: