No F*cking Idea

Common answer to everything

Shortest Way to Work With Json in Haskell

| Comments

Data.Aeson is a great package for working with json data in Haskell but you can make it work even in fewer lines of code.

if you will use DeriveGeneric from GHC and GHC.Generics in your module you can parse stuff super easy ;O.

This is my example that explains how to use it.

json_example.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}

import Data.Aeson
import GHC.Generics

data Profile = Profile {
  age       :: Int,
  isNice    :: Bool
} deriving (Show, Generic)

data User = User {
  id        :: Int,
  name      :: String,
  profile   :: Profile
} deriving (Show, Generic)

instance FromJSON Profile
instance ToJSON Profile

instance FromJSON User
instance ToJSON User

main = do
  let profile = Profile 29 True
  let user = User 1 "Kuba" profile
  putStrLn $ show user

  -- encode will give you back ByteString

  let json = encode user
  putStrLn $ show json

  -- decode will give you back Maybe

  let parsedUser = decode json :: Maybe User
  case parsedUser of
    Just newUser -> putStrLn $ show newUser
    Nothing -> putStrLn "Sorry mate this is not happening"

result

result
1
2
3
User {id = 1, name = "Kuba", profile = Profile {age = 29, isNice = True}}
"{\"id\":1,\"name\":\"Kuba\",\"profile\":{\"isNice\":true,\"age\":29}}"
User {id = 1, name = "Kuba", profile = Profile {age = 29, isNice = True}}

Here i made shortest possible example to show off how you can work with Aeson. First of all if you will use Generics you don’t have to write real implementation of ToJSON and FromJSON GHC will do this or you!

Only thing to remember is that encode will give you back ByteString and decode will give you Maybe A and thats it.

You always can fallback to normal way of describing FromJSON and ToJSON :)

Comments