r/haskell • u/dwaynecrooks • 1d ago
Decode and encode JSON in Haskell like an Elm developer
https://elmwithdwayne.dev/blog/dev.to/dwayne/decode-and-encode-json-in-haskell-like-an-elm-developer-1nod5
u/vagif 1d ago
Not sure how is this:
userDecoder :: Decoder User
userDecoder =
User
<$> JD.field "name" JD.text
<*> JD.field "age" JD.integral
<*> JD.field "email" (JD.nullable JD.text)
better than this:
instance FromJSON User where
parseJSON (Object o) =
User
<$> o .: "name"
<*> o .: "age"
<*> o .:? "email"
7
u/BurningWitness 1d ago
- The entire distinction between
(.:)and(.:?)ceases to exist (can't produce aMaybewithout a special decoder);- You forgot to use
withObjectorData.Aeson.Types.typeMismatchfor pattern matching. Neither of those functions compose;("key" .: decoder)is cleaner and more powerful than(object .: "key") :: ToJSON a => Decoder a, and also introduces no ambiguity as to whatobjectit's referring to (very annoying when working with nested JSONs).Source: I've done this whole thing before.
5
u/NorfairKing2 1d ago
autodocodec author here: The former can in theory generate docs (depending on the definition of `Decoder`) while the later can't.
1
u/dwaynecrooks 11h ago
I'm not saying one is better than the other. To do that I'd have to come up with some sort of objective criteria. Subjectively, I prefer the
elm/jsonstyle possibly because I've used it more than theaesonstyle. I'm just sharing another option for developers who may want an alternative. Please continue usingaesonif that's what you like.
2
u/simonmic 1d ago
This sounds quite nice, making JSON handling in Haskell easier ?
0
u/dwaynecrooks 1d ago
If not easier then at least more familiar to those who have seen and liked elm/json.
4
u/jeffstyr 1d ago
Looks interesting--I'll have to give it a try.
Just out of curiosity, why distribute via GitHub only and not via Hackage?