Menu

1 / 2

Decode and encode JSON in Haskell like an Elm developer

DEV Community: haskell·Dwayne Crooks·5 days ago
#g9ZFvnVk
#devtohaskell#devto#dev#json#decoder
Reading 0:00
15s threshold

If you're an Elm developer writing Haskell and you like elm/json , you might like dwayne/hs-json-codec .

hs-json-codec provides JSON decoders and encoders for Haskell in the style of elm/json . It's built on dwayne/hs-json-parser , a general-purpose JSON parser and printer that I also wrote.

I built both libraries because I wanted them for dwayne/elm2nix , but they can be used in any Haskell project. In this post, I'll introduce their APIs and show how I use them in elm2nix .

Decoding JSON

Let's start with a small example. Given this Haskell type:

data User = User { name :: Text , age :: Int , email :: Maybe Text } deriving ( Eq , Show )

Enter fullscreen mode

Exit fullscreen mode

You can build a decoder by combining smaller decoders:

import qualified Json.Decode as JD

import Json.Decode ( Decoder )

userDecoder :: Decoder User userDecoder = User <$> JD . field "name" JD . text <*> JD . field "age" JD . integral <*> JD . field "email" ( JD . nullable JD .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.