|
146 | 146 |
|
147 | 147 | defimpl JSON.Encoder, for: Map do
|
148 | 148 | def encode(value, encoder) do
|
149 |
| - :elixir_json.encode_map(value, encoder) |
| 149 | + case :maps.next(:maps.iterator(value)) do |
| 150 | + :none -> |
| 151 | + "{}" |
| 152 | + |
| 153 | + {key, value, iterator} -> |
| 154 | + [?{, key(key, encoder), ?:, encoder.(value, encoder) | next(iterator, encoder)] |
| 155 | + end |
150 | 156 | end
|
| 157 | + |
| 158 | + defp next(iterator, encoder) do |
| 159 | + case :maps.next(iterator) do |
| 160 | + :none -> |
| 161 | + "}" |
| 162 | + |
| 163 | + {key, value, iterator} -> |
| 164 | + [?,, key(key, encoder), ?:, encoder.(value, encoder) | next(iterator, encoder)] |
| 165 | + end |
| 166 | + end |
| 167 | + |
| 168 | + # Erlang supports only numbers, binaries, and atoms as keys, |
| 169 | + # we support anything that implements the String.Chars protocol. |
| 170 | + defp key(key, encoder) when is_atom(key), do: encoder.(Atom.to_string(key), encoder) |
| 171 | + defp key(key, encoder) when is_binary(key), do: encoder.(key, encoder) |
| 172 | + defp key(key, encoder), do: encoder.(String.Chars.to_string(key), encoder) |
151 | 173 | end
|
152 | 174 |
|
153 | 175 | defimpl JSON.Encoder, for: [Date, Time, NaiveDateTime, DateTime, Duration] do
|
@@ -175,17 +197,15 @@ defmodule JSON do
|
175 | 197 |
|
176 | 198 | Elixir built-in data structures are encoded to JSON as follows:
|
177 | 199 |
|
178 |
| - | **Elixir** | **JSON** | |
179 |
| - |------------------------|----------| |
180 |
| - | `integer() \| float()` | Number | |
181 |
| - | `true \| false ` | Boolean | |
182 |
| - | `nil` | Null | |
183 |
| - | `binary()` | String | |
184 |
| - | `atom()` | String | |
185 |
| - | `list()` | Array | |
186 |
| - | `%{binary() => _}` | Object | |
187 |
| - | `%{atom() => _}` | Object | |
188 |
| - | `%{integer() => _}` | Object | |
| 200 | + | **Elixir** | **JSON** | |
| 201 | + |----------------------------|----------| |
| 202 | + | `integer() \| float()` | Number | |
| 203 | + | `true \| false ` | Boolean | |
| 204 | + | `nil` | Null | |
| 205 | + | `binary()` | String | |
| 206 | + | `atom()` | String | |
| 207 | + | `list()` | Array | |
| 208 | + | `%{String.Chars.t() => _}` | Object | |
189 | 209 |
|
190 | 210 | You may also implement the `JSON.Encoder` protocol for custom data structures.
|
191 | 211 |
|
@@ -403,7 +423,7 @@ defmodule JSON do
|
403 | 423 | do: :elixir_json.encode_list(value, encoder)
|
404 | 424 |
|
405 | 425 | def protocol_encode(%{} = value, encoder) when not is_map_key(value, :__struct__),
|
406 |
| - do: :elixir_json.encode_map(value, encoder) |
| 426 | + do: JSON.Encoder.Map.encode(value, encoder) |
407 | 427 |
|
408 | 428 | def protocol_encode(value, encoder),
|
409 | 429 | do: JSON.Encoder.encode(value, encoder)
|
|
0 commit comments