Switch daemon startup to pipe-based error reporting
[ganeti-local] / htools / Ganeti / JSON.hs
index 132c0b2..178915a 100644 (file)
@@ -31,6 +31,8 @@ module Ganeti.JSON
   , fromObjWithDefault
   , fromKeyValue
   , fromJVal
+  , jsonHead
+  , getMaybeJsonHead
   , asJSObject
   , asObjectList
   , tryFromObj
@@ -125,6 +127,16 @@ fromJVal v =
                        "', error: " ++ s)
     J.Ok x -> return x
 
+-- | Helper function that returns Null or first element of the list.
+jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
+jsonHead [] _ = J.JSNull
+jsonHead (x:_) f = J.showJSON $ f x
+
+-- | Helper for extracting Maybe values from a possibly empty list.
+getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
+getMaybeJsonHead [] _ = J.JSNull
+getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
+
 -- | Converts a JSON value into a JSON object.
 asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
 asJSObject (J.JSObject a) = return a