Revision 964a728f src/Ganeti/JSON.hs

b/src/Ganeti/JSON.hs
26 26

  
27 27
module Ganeti.JSON
28 28
  ( fromJResult
29
  , fromJResultE
29 30
  , readEitherString
30 31
  , JSRecord
31 32
  , loadJSArray
......
34 35
  , fromObjWithDefault
35 36
  , fromKeyValue
36 37
  , fromJVal
38
  , fromJValE
37 39
  , jsonHead
38 40
  , getMaybeJsonHead
39 41
  , getMaybeJsonElem
......
54 56

  
55 57
import Control.DeepSeq
56 58
import Control.Monad (liftM)
59
import Control.Monad.Error.Class
57 60
import Data.Maybe (fromMaybe, catMaybes)
58 61
import qualified Data.Map as Map
59 62
import Text.Printf (printf)
......
91 94
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
92 95
fromJResult _ (J.Ok x) = return x
93 96

  
97
-- | Converts a JSON Result into a MonadError value.
98
fromJResultE :: (Error e, MonadError e m) => String -> J.Result a -> m a
99
fromJResultE s (J.Error x) = throwError . strMsg $ s ++ ": " ++ x
100
fromJResultE _ (J.Ok x) = return x
101

  
94 102
-- | Tries to read a string from a JSON value.
95 103
--
96 104
-- In case the value was not a string, we fail the read (in the
......
185 193
                       "', error: " ++ s)
186 194
    J.Ok x -> return x
187 195

  
196
-- | Small wrapper over 'readJSON' for 'MonadError'.
197
fromJValE :: (Error e, MonadError e m, J.JSON a) => J.JSValue -> m a
198
fromJValE v =
199
  case J.readJSON v of
200
    J.Error s -> throwError . strMsg $
201
                  "Cannot convert value '" ++ show (pp_value v) ++
202
                  "', error: " ++ s
203
    J.Ok x -> return x
204

  
188 205
-- | Helper function that returns Null or first element of the list.
189 206
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
190 207
jsonHead [] _ = J.JSNull

Also available in: Unified diff