Skip to content

Commit 1a2c91d

Browse files
authored
Implement JSON.Encoder if available (#215)
1 parent 045403e commit 1a2c91d

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

lib/decimal.ex

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2095,3 +2095,12 @@ defimpl String.Chars, for: Decimal do
20952095
Decimal.to_string(dec)
20962096
end
20972097
end
2098+
2099+
# TODO: remove when we require Elixir 1.18
2100+
if Code.ensure_loaded?(JSON.Encoder) and function_exported?(JSON.Encoder, :encode, 2) do
2101+
defimpl JSON.Encoder, for: Decimal do
2102+
def encode(decimal, _encoder) do
2103+
[?", Decimal.to_string(decimal), ?"]
2104+
end
2105+
end
2106+
end

test/decimal_test.exs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,4 +934,10 @@ defmodule DecimalTest do
934934
Decimal.sqrt(Decimal.new(d(3, 1, -1)))
935935
end
936936
end
937+
938+
if Version.match?(System.version(), ">= 1.18.0-rc") do
939+
test "JSON.Encoder implementation" do
940+
assert JSON.encode!(%{x: Decimal.new("1.0")}) == "{\"x\":\"1.0\"}"
941+
end
942+
end
937943
end

0 commit comments

Comments
 (0)