# `JSON.Encoder`
[🔗](https://github.com/elixir-lang/elixir/blob/v1.20.1/lib/elixir/lib/json.ex#L4)

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 {: .error}
>
> 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)

# `t`

```elixir
@type t() :: term()
```

All the types that implement this protocol.

# `encode`

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

---

*Consult [api-reference.md](api-reference.md) for complete listing*
