JSON.Encoder protocol (Elixir v1.20.0-dev)

View Source

A protocol for custom JSON encoding of data structures.

If you have a struct, you can derive the implementation of this protocol by specifying which fields should be encoded to JSON:

@derive {JSON.Encoder, only: [...]}
defstruct ...

Additionally, you can exclude specific fields using the :except option or encode all fields by omitting both options entirely, but these should be used with caution:

@derive {JSON.Encoder, except: [...]}
defstruct ...

@derive JSON.Encoder
defstruct ...

Leaking Private Information

Prefer using :only to avoid accidentally leaking private information when new fields are added. Other approaches should be used with auction.

You can also use Protocol.derive/3 if you don't own the struct that you want to encode to JSON:

Protocol.derive(JSON.Encoder, NameOfTheStruct, only: [...])
Protocol.derive(JSON.Encoder, NameOfTheStruct, except: [...])
Protocol.derive(JSON.Encoder, NameOfTheStruct)

Summary

Types

t()

All the types that implement this protocol.

Functions

A function invoked to encode the given term to iodata/0.

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

encode(term, encoder)

A function invoked to encode the given term to iodata/0.