62 lines
1.6 KiB
Markdown
62 lines
1.6 KiB
Markdown
|
|
# Haskell Generic JSON
|
||
|
|
|
||
|
|
This note covers `38-haskell-generic-json/`, which derives JSON instances generically for a release manifest and rollout strategy.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 1. Why This Exists Next to the Manual JSON Example
|
||
|
|
|
||
|
|
`27-haskell-aeson-roundtrip/` defines JSON instances by hand so the wire format stays fully explicit.
|
||
|
|
|
||
|
|
This example shows the contrasting approach:
|
||
|
|
|
||
|
|
- derive `Generic`,
|
||
|
|
- configure Aeson options once, and
|
||
|
|
- let `genericToJSON` and `genericParseJSON` do the repetitive instance work.
|
||
|
|
|
||
|
|
That is useful because both styles show up in real Haskell codebases.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 2. What the Generic Options Control
|
||
|
|
|
||
|
|
The example is not just `deriving anyclass`.
|
||
|
|
|
||
|
|
It still configures the shape:
|
||
|
|
|
||
|
|
- field labels drop the `manifest` prefix, and
|
||
|
|
- the rollout strategy sum type uses a tagged object representation.
|
||
|
|
|
||
|
|
That is the important teaching point. Generic deriving can still produce an intentional JSON format when you provide the right options.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 3. When This Tradeoff Makes Sense
|
||
|
|
|
||
|
|
Generic deriving reduces boilerplate when:
|
||
|
|
|
||
|
|
- your Haskell fields already describe the desired structure closely, and
|
||
|
|
- you want the encoder and decoder to stay in sync with minimal manual code.
|
||
|
|
|
||
|
|
It is less appropriate when the wire format needs heavy customization. That contrast is exactly why it is useful to pair this example with the manual
|
||
|
|
JSON example earlier in the track.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 4. Commands to Try
|
||
|
|
|
||
|
|
```bash
|
||
|
|
cd 38-haskell-generic-json
|
||
|
|
|
||
|
|
nix develop
|
||
|
|
cabal run
|
||
|
|
cabal run -- api production 3 platform,security stable
|
||
|
|
cabal test
|
||
|
|
|
||
|
|
nix build
|
||
|
|
./result/bin/mini-generic-json api production 3 platform,security stable
|
||
|
|
|
||
|
|
nix run . -- api production 3 platform,security stable
|
||
|
|
nix flake check
|
||
|
|
```
|