Skip to content

Commit

Permalink
Implement JSON.Encoder for Calendar types (#14061)
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim authored Dec 11, 2024
1 parent fb288a4 commit 8a0cd66
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
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
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

0 comments on commit 8a0cd66

Please sign in to comment.