AE

Aeson

Aeson JSON library patterns for type-safe JSON encoding and decoding in Haskell

Details

Language / Topic
haskellHaskell
Category
Libraries

Rules

balanced
- Derive instances with `deriving (Generic)` and `instance ToJSON User; instance FromJSON User` — GHC Generic avoids manual boilerplate.
- Use `eitherDecodeStrict bs :: Either String User` for safe parsing — never use `decode` that returns `Maybe` and silently discards errors.
- Encode with `Data.Aeson.encode value` to a lazy `ByteString` or `Data.Aeson.encodeFile path value` to write directly to disk.
- Customise field names with `genericToJSON defaultOptions { fieldLabelModifier = camelToSnake }` — avoids `_` prefixes leaking into JSON output.
- Use `(.:)` for required fields and `(.:?)` for optional fields in manual `FromJSON` instances: `v .: "name" <*> v .:? "age"`.
- Rename fields per-instance: `genericParseJSON defaultOptions { fieldLabelModifier = drop 4 }` strips a 4-char type prefix.
- Use `withObject "User" \v -> User <$> v .: "name" <*> v .: "email"` for clear, self-documenting manual decoders.
- Construct ad-hoc JSON with `object ["key" .= value, "count" .= n]` — useful for one-off response shapes.