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

Implement JSON.Encoder for Calendar types #14061

Merged
merged 1 commit into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions lib/elixir/lib/json.ex
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ defimpl JSON.Encoder, for: Map do
end
end

defimpl JSON.Encoder, for: [Date, Time, NaiveDateTime, DateTime] do
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should Duration also be included?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I asked myself the same and, honestly, I am not sure. We could easily use the ISO representation, but I am not sure how widespread it is, it is definitely less common than the datetime ones.

Copy link

@Wigny Wigny Dec 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK, in the JS world it is common to serialise duration as ISO strings when parsing it to JSON (see Temporal.Duration.toJSON or dayjs.duration). As the string format chose in serialization is just a convention, I hopped ISO strings was a good enough format to be used as default.

def encode(value, _encoder) do
[?", @for.to_iso8601(value), ?"]
end
end

defmodule JSON.DecodeError do
@moduledoc """
The exception raised by `JSON.decode!/1`.
Expand Down
7 changes: 7 additions & 0 deletions lib/elixir/test/elixir/json_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ defmodule JSONTest do
assert JSON.encode!(%Token{value: :example}) == "[\"example\"]"
assert JSON.encode!(%Token{value: "hello\0world"}) == "[\"hello\\u0000world\"]"
end

test "calendar" do
assert JSON.encode!(~D[2010-04-17]) == "\"2010-04-17\""
assert JSON.encode!(~T[14:00:00.123]) == "\"14:00:00.123\""
assert JSON.encode!(~N[2010-04-17 14:00:00.123]) == "\"2010-04-17T14:00:00.123\""
assert JSON.encode!(~U[2010-04-17 14:00:00.123Z]) == "\"2010-04-17T14:00:00.123Z\""
end
end

describe "JSON.Encoder" do
Expand Down
Loading