module Ganeti.HTools.JSON
( fromJResult
, readEitherString
, JSRecord
, loadJSArray
, fromObj
, maybeFromObj
, fromObjWithDefault
, fromKeyValue
, fromJVal
, asJSObject
, asObjectList
, tryFromObj
, toArray
)
where
import Control.Monad (liftM)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
import qualified Text.JSON as J
import Ganeti.BasicTypes
type JSRecord = [(String, J.JSValue)]
fromJResult :: Monad m => String -> J.Result a -> m a
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
fromJResult _ (J.Ok x) = return x
readEitherString :: (Monad m) => J.JSValue -> m String
readEitherString v =
case v of
J.JSString s -> return $ J.fromJSString s
_ -> fail "Wrong JSON type"
loadJSArray :: (Monad m)
=> String
-> String
-> m [J.JSObject J.JSValue]
loadJSArray s = fromJResult s . J.decodeStrict
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
fromObj o k =
case lookup k o of
Nothing -> fail $ printf "key '%s' not found, object contains only %s"
k (show (map fst o))
Just val -> fromKeyValue k val
maybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m (Maybe a)
maybeFromObj o k =
case lookup k o of
Nothing -> return Nothing
Just val -> liftM Just (fromKeyValue k val)
fromObjWithDefault :: (J.JSON a, Monad m) =>
JSRecord -> String -> a -> m a
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
fromKeyValue :: (J.JSON a, Monad m)
=> String
-> J.JSValue
-> m a
fromKeyValue k val =
fromJResult (printf "key '%s'" k) (J.readJSON val)
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
fromJVal v =
case J.readJSON v of
J.Error s -> fail ("Cannot convert value '" ++ show v ++
"', error: " ++ s)
J.Ok x -> return x
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
asJSObject (J.JSObject a) = return a
asJSObject _ = fail "not an object"
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
asObjectList = mapM asJSObject
tryFromObj :: (J.JSON a) =>
String
-> JSRecord
-> String
-> Result a
tryFromObj t o = annotateResult t . fromObj o
toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
toArray (J.JSArray arr) = return arr
toArray o = fail $ "Invalid input, expected array but got " ++ show o