Install Jason via mix
masterTo use Jason in your Elixir project, add it to your deps in mix.exs.
def deps do
[{:jason, "~> 1.4"}]
endrepository·master·Indexed 23 days ago
https://github.com/michalmuskala/jasonA high-performance JSON parser and generator written in pure Elixir. Provides functions for encoding and decoding data structures via Jason.encode!/1 and Jason.decode!/1, support for custom types through the Jason.Encoder protocol, and optimization via Jason.Fragment.
To use Jason in your Elixir project, add it to your deps in mix.exs.
def deps do
[{:jason, "~> 1.4"}]
endJason.encode!/1 to convert an Elixir data structure to a JSON string, and Jason.decode!/1 to parse a JSON string into an Elixir data structure. The bang versions (!) will raise an error on failure.When using Absinthe, you must explicitly pass json_codec: Jason to Absinthe.Plug via the :json_codec option.
# When called directly:
plug Absinthe.Plug,
schema: MyApp.Schema,
json_codec: Jason
# When used in phoenix router:
forward "/api",
to: Absinthe.Plug,
init_opts: [schema: MyApp.Schema, json_codec: Jason]Protocol.derive/3 to implement the Jason.Encoder protocol externally.If you own a struct, you can use @derive to implement the Jason.Encoder protocol. You can specify which fields to include using the only: option, or encode all fields by omitting it.
# Specify specific fields
@derive {Jason.Encoder, only: [....]}
defstruct # ...
# Encode all fields (use carefully)
@derive Jason.Encoder
defstruct # ...Jason does not support decoding into specific data structures (no as: option) and does not have built-in encoders for MapSet, Range, or Stream. You can implement the Jason.Encoder protocol manually for these types.
defimpl Jason.Encoder, for: [MapSet, Range, Stream] do
def encode(struct, opts) do
Jason.Encode.list(Enum.to_list(struct), opts)
end
endTo avoid unnecessary decoding/encoding roundtrips, use Jason.Fragment.new/1 to mark parts of a structure that are already valid JSON strings.
already_encoded_json = Jason.encode!(%{hello: "world"})
Jason.encode!(%{foo: Jason.Fragment.new(already_encoded_json)})