/ src / Utils / JSON.hs
JSON.hs
 1  module Utils.JSON (parseStringifiedObject, stringifyObject, parseNonEmpty) where
 2  
 3  import Data.Aeson (FromJSON, ToJSON, eitherDecode, encode)
 4  import Data.Aeson.Types (Parser)
 5  import qualified Data.ByteString.Lazy.Char8 as BSL8
 6  import qualified Data.Text as T
 7  import Data.Text.Encoding (encodeUtf8)
 8  
 9  parseStringifiedObject :: (FromJSON a) => T.Text -> Parser a
10  parseStringifiedObject txt = case eitherDecode $ BSL8.fromStrict $ encodeUtf8 txt of
11    Left err -> fail $ "Failed to decode serialized object " ++ err
12    Right val -> pure val
13  
14  stringifyObject :: (ToJSON a) => a -> T.Text
15  stringifyObject = T.pack . BSL8.unpack . encode
16  
17  parseNonEmpty :: String -> T.Text -> Parser T.Text
18  parseNonEmpty fieldName txt
19    | T.null txt = fail $ fieldName ++ " must be non-empty"
20    | otherwise = pure txt