Created
October 26, 2016 07:42
-
-
Save afcondon/2bb3833ffb43986994266d373f9676bb to your computer and use it in GitHub Desktop.
Pulling a record (ie naked JSON object) of one of two types out of a JSON string using purescript-argonaut and Alt instance of Either
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Prelude | |
import Control.Alt ((<|>)) | |
import Data.Argonaut (Json, decodeJson, (.?)) | |
import Data.Either (Either) | |
data Response = A { commandResponse :: String, value :: String } | |
| B { command :: String, value :: Int } | |
decodeResponse :: Json -> Either String Response | |
decodeResponse json = decodeA json <|> decodeB json | |
decodeA :: Json -> Either String Response | |
decodeA json = do | |
obj <- decodeJson json | |
r <- obj .? "commandResponse" | |
v <- obj .? "value" | |
pure (A { commandResponse: r, value: v }) | |
decodeB :: Json -> Either String Response | |
decodeB json = do | |
obj <- decodeJson json | |
r <- obj .? "command" | |
v <- obj .? "value" | |
pure (B { command: r, value: v }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment