Jason Documentation

repository·master·Indexed 23 days ago

https://github.com/michalmuskala/jason

A 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.

Tokens
639
Snippets
5
Records
7
Agent score
32%

What's inside Jason

  1. Configure Jason for Absinthe

    master

    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]
  2. Derive Jason.Encoder for structs

    master

    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 # ...
  3. Implement Jason.Encoder for custom types

    master

    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
    end
  4. Inject pre-encoded JSON using Jason.Fragment

    master

    To 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)})