Fix a couple of bugs in handling offline instances
[ganeti-local] / htools / Ganeti / HTools / JSON.hs
index 6fe45ba..31a6d19 100644 (file)
@@ -29,9 +29,11 @@ module Ganeti.HTools.JSON
   , fromObj
   , maybeFromObj
   , fromObjWithDefault
+  , fromKeyValue
   , fromJVal
   , asJSObject
   , asObjectList
+  , tryFromObj
   )
   where
 
@@ -41,6 +43,8 @@ import Text.Printf (printf)
 
 import qualified Text.JSON as J
 
+import Ganeti.BasicTypes
+
 -- * JSON-related functions
 
 -- | A type alias for the list-based representation of J.JSObject.
@@ -95,7 +99,7 @@ fromKeyValue :: (J.JSON a, Monad m)
               -> J.JSValue  -- ^ The value to read
               -> m a
 fromKeyValue k val =
-  fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
+  fromJResult (printf "key '%s'" k) (J.readJSON val)
 
 -- | Small wrapper over readJSON.
 fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
@@ -113,3 +117,12 @@ asJSObject _ = fail "not an object"
 -- | Coneverts a list of JSON values into a list of JSON objects.
 asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
 asObjectList = mapM asJSObject
+
+-- | Try to extract a key from a object with better error reporting
+-- than fromObj.
+tryFromObj :: (J.JSON a) =>
+              String     -- ^ Textual "owner" in error messages
+           -> JSRecord   -- ^ The object array
+           -> String     -- ^ The desired key from the object
+           -> Result a
+tryFromObj t o = annotateResult t . fromObj o