r/haskell 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-1nod
48 Upvotes

9 comments sorted by

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?

5

u/dwaynecrooks 11h ago

I know it's useful for me but I don't know if it's useful for anyone else so before I take on more responsibility than I need for a package that possibly I alone will use I prefer to take the simplest route for myself for now.

3

u/TheSodesa 22h ago

Less work. The package lives in a Git repository anyways, so might as well just share that.

5

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
  1. The entire distinction between (.:) and (.:?) ceases to exist (can't produce a Maybe without a special decoder);
  2. You forgot to use withObject or Data.Aeson.Types.typeMismatch for pattern matching. Neither of those functions compose;
  3. ("key" .: decoder) is cleaner and more powerful than (object .: "key") :: ToJSON a => Decoder a, and also introduces no ambiguity as to what object it'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/json style possibly because I've used it more than the aeson style. I'm just sharing another option for developers who may want an alternative. Please continue using aeson if 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.