Revision 28f19313 htools/Ganeti/HTools/Utils.hs
b/htools/Ganeti/HTools/Utils.hs | ||
---|---|---|
30 | 30 |
, stdDev |
31 | 31 |
, commaJoin |
32 | 32 |
, readEitherString |
33 |
, JSRecord |
|
33 | 34 |
, loadJSArray |
34 | 35 |
, fromObj |
35 | 36 |
, fromObjWithDefault |
... | ... | |
106 | 107 |
|
107 | 108 |
-- * JSON-related functions |
108 | 109 |
|
110 |
-- | A type alias for the list-based representation of J.JSObject |
|
111 |
type JSRecord = [(String, J.JSValue)] |
|
112 |
|
|
109 | 113 |
-- | Converts a JSON Result into a monadic value. |
110 | 114 |
fromJResult :: Monad m => String -> J.Result a -> m a |
111 | 115 |
fromJResult s (J.Error x) = fail (s ++ ": " ++ x) |
... | ... | |
129 | 133 |
loadJSArray s = fromJResult s . J.decodeStrict |
130 | 134 |
|
131 | 135 |
-- | Reads the value of a key in a JSON object. |
132 |
fromObj :: (J.JSON a, Monad m) => [(String, J.JSValue)] -> String -> m a
|
|
136 |
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
|
|
133 | 137 |
fromObj o k = |
134 | 138 |
case lookup k o of |
135 | 139 |
Nothing -> fail $ printf "key '%s' not found, object contains only %s" |
... | ... | |
138 | 142 |
|
139 | 143 |
-- | Reads the value of an optional key in a JSON object. |
140 | 144 |
maybeFromObj :: (J.JSON a, Monad m) => |
141 |
[(String, J.JSValue)] -> String -> m (Maybe a)
|
|
145 |
JSRecord -> String -> m (Maybe a)
|
|
142 | 146 |
maybeFromObj o k = |
143 | 147 |
case lookup k o of |
144 | 148 |
Nothing -> return Nothing |
... | ... | |
146 | 150 |
|
147 | 151 |
-- | Reads the value of a key in a JSON object with a default if missing. |
148 | 152 |
fromObjWithDefault :: (J.JSON a, Monad m) => |
149 |
[(String, J.JSValue)] -> String -> a -> m a
|
|
153 |
JSRecord -> String -> a -> m a
|
|
150 | 154 |
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k |
151 | 155 |
|
152 | 156 |
-- | Reads a JValue, that originated from an object key |
... | ... | |
165 | 169 |
-- | Try to extract a key from a object with better error reporting |
166 | 170 |
-- than fromObj |
167 | 171 |
tryFromObj :: (J.JSON a) => |
168 |
String -- ^ Textual "owner" in error messages
|
|
169 |
-> [(String, J.JSValue)] -- ^ The object array
|
|
170 |
-> String -- ^ The desired key from the object
|
|
172 |
String -- ^ Textual "owner" in error messages |
|
173 |
-> JSRecord -- ^ The object array
|
|
174 |
-> String -- ^ The desired key from the object |
|
171 | 175 |
-> Result a |
172 | 176 |
tryFromObj t o = annotateResult t . fromObj o |
173 | 177 |
|
Also available in: Unified diff