Commit 3c8e6d09 authored by Michele Tartara's avatar Michele Tartara
Browse files

Add two support functions for building JSON objects



The new support functions in module Ganeti.JSON will be used by the next
commits to build JSON objects with optional (Maybe) fields, excluding
them when they contain Nothing.
Signed-off-by: default avatarMichele Tartara <mtartara@google.com>
Reviewed-by: default avatarIustin Pop <iustin@google.com>
parent 086ad4cf
......@@ -38,6 +38,8 @@ module Ganeti.JSON
, asObjectList
, tryFromObj
, toArray
, optionalJSField
, optFieldsToObj
, HasStringRepr(..)
, GenericContainer(..)
, Container
......@@ -45,7 +47,7 @@ module Ganeti.JSON
where
import Control.Monad (liftM)
import Data.Maybe (fromMaybe)
import Data.Maybe (fromMaybe, catMaybes)
import qualified Data.Map as Map
import Text.Printf (printf)
......@@ -60,8 +62,11 @@ import Ganeti.BasicTypes
-- * JSON-related functions
-- | A type alias for a field of a JSRecord.
type JSField = (String, J.JSValue)
-- | A type alias for the list-based representation of J.JSObject.
type JSRecord = [(String, J.JSValue)]
type JSRecord = [JSField]
-- | Converts a JSON Result into a monadic value.
fromJResult :: Monad m => String -> J.Result a -> m a
......@@ -167,6 +172,16 @@ toArray (J.JSArray arr) = return arr
toArray o =
fail $ "Invalid input, expected array but got " ++ show (pp_value o)
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField
-- will be Nothing as well.
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
optionalJSField name (Just value) = Just (name, J.showJSON value)
optionalJSField _ Nothing = Nothing
-- | Creates an object with all the non-Nothing fields of the given list.
optFieldsToObj :: [Maybe JSField] -> J.JSValue
optFieldsToObj = J.makeObj . catMaybes
-- * Container type (special type for JSON serialisation)
-- | Class of types that can be converted from Strings. This is
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment