/
json.ex
48 lines (37 loc) · 1.4 KB
/
json.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
defmodule JSON do
@doc """
Returns a JSON string representation of the Elixir term
## Examples
iex> JSON.encode([result: "this will be a elixir result"])
{:ok, "{\\\"result\\\":\\\"this will be a elixir result\\\"}"}
"""
@spec encode(term) :: {atom, bitstring}
def encode(term), do: JSON.Encode.to_json(term)
@spec encode!(term) :: bitstring
def encode!(term) do
case encode(term) do
{ :ok, value } -> value
{ :error, error_info } -> raise JSON.Encode.Error, error_info: error_info
_ -> raise JSON.Encode.Error
end
end
@doc """
Converts a valid JSON string into an Elixir term
## Examples
iex> JSON.decode("{\\\"result\\\":\\\"this will be a elixir result\\\"}")
{:ok, HashDict.new [{"result", "this will be a elixir result"}]}
"""
@spec decode(bitstring) :: {atom, term}
@spec decode(char_list) :: {atom, term}
def decode(string), do: JSON.Decode.from_json(string)
@spec decode!(bitstring) :: term
@spec decode!(char_list) :: term
def decode!(bitstring) do
case decode(bitstring) do
{ :ok, value } -> value
{ :unexpected_token, tok } -> raise JSON.Decode.UnexpectedTokenError, token: tok
{ :unexpected_end_of_buffer, _ } -> raise JSON.Decode.UnexpectedEndOfBufferError
_ -> raise JSON.Decode.Error
end
end
end