defmodule JSON do @moduledoc """ Provides a RFC 7159, ECMA 404, and JSONTestSuite compliant JSON Encoder / Decoder """ alias JSON.Encoder, as: Encoder alias Encoder.Error, as: EncoderError alias JSON.Decoder, as: Decoder alias Decoder.UnexpectedTokenError, as: UnexpectedTokenError alias Decoder.UnexpectedEndOfBufferError, as: UnexpectedEndOfBufferError alias Decoder.Error, as: UnknownDecoderError @vsn "2.0.0-SNAPSHOT" @compile [:native, {:hipe, [:o3]}] @doc """ Returns a JSON string representation of the Elixir term ## Examples iex> JSON.encode([result: "this will be a JSON result"]) {:ok, "{\\\"result\\\":\\\"this will be a JSON result\\\"}"} """ @spec encode(term) :: {atom, bitstring} defdelegate encode(term), to: Encoder @doc """ Returns a JSON string representation of the Elixir term, raises errors when something bad happens ## Examples iex> JSON.encode!([result: "this will be a JSON result"]) "{\\\"result\\\":\\\"this will be a JSON result\\\"}" """ @spec encode!(term) :: bitstring def encode!(term) do case encode(term) do {:ok, value} -> value {:error, error_info} -> raise EncoderError, error_info: error_info _ -> raise EncoderError end end @doc """ Converts a valid JSON string into an Elixir term ## Examples iex> JSON.decode("{\\\"result\\\":\\\"this will be an Elixir result\\\"}") {:ok, Enum.into([{"result", "this will be an Elixir result"}], Map.new)} """ @spec decode(bitstring) :: {atom, term} @spec decode(charlist) :: {atom, term} defdelegate decode(bitstring_or_char_list), to: Decoder @doc """ Converts a valid JSON string into an Elixir term, raises errors when something bad happens ## Examples iex> JSON.decode!("{\\\"result\\\":\\\"this will be an Elixir result\\\"}") Enum.into([{"result", "this will be an Elixir result"}], Map.new) """ @spec decode!(bitstring) :: term @spec decode!(charlist) :: term def decode!(bitstring_or_char_list) do case decode(bitstring_or_char_list) do {:ok, value} -> value {:error, {:unexpected_token, tok}} -> raise UnexpectedTokenError, token: tok {:error, :unexpected_end_of_buffer} ->raise UnexpectedEndOfBufferError _ -> raise UnknownDecoderError end end end