1 {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
4 {-| JSON utility functions. -}
8 Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
46 , GenericContainer(..)
51 import Control.DeepSeq
52 import Control.Monad (liftM)
53 import Data.Maybe (fromMaybe, catMaybes)
54 import qualified Data.Map as Map
55 import Text.Printf (printf)
57 import qualified Text.JSON as J
58 import Text.JSON.Pretty (pp_value)
60 -- Note: this module should not import any Ganeti-specific modules
61 -- beside BasicTypes, since it's used in THH which is used itself to
62 -- build many other modules.
64 import Ganeti.BasicTypes
66 -- * JSON-related functions
68 instance NFData J.JSValue where
70 rnf (J.JSBool b) = rnf b
71 rnf (J.JSRational b r) = rnf b `seq` rnf r
72 rnf (J.JSString s) = rnf $ J.fromJSString s
73 rnf (J.JSArray a) = rnf a
74 rnf (J.JSObject o) = rnf o
76 instance (NFData a) => NFData (J.JSObject a) where
77 rnf = rnf . J.fromJSObject
79 -- | A type alias for a field of a JSRecord.
80 type JSField = (String, J.JSValue)
82 -- | A type alias for the list-based representation of J.JSObject.
83 type JSRecord = [JSField]
85 -- | Converts a JSON Result into a monadic value.
86 fromJResult :: Monad m => String -> J.Result a -> m a
87 fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
88 fromJResult _ (J.Ok x) = return x
90 -- | Tries to read a string from a JSON value.
92 -- In case the value was not a string, we fail the read (in the
93 -- context of the current monad.
94 readEitherString :: (Monad m) => J.JSValue -> m String
97 J.JSString s -> return $ J.fromJSString s
98 _ -> fail "Wrong JSON type"
100 -- | Converts a JSON message into an array of JSON objects.
101 loadJSArray :: (Monad m)
102 => String -- ^ Operation description (for error reporting)
103 -> String -- ^ Input message
104 -> m [J.JSObject J.JSValue]
105 loadJSArray s = fromJResult s . J.decodeStrict
107 -- | Reads the value of a key in a JSON object.
108 fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
111 Nothing -> fail $ printf "key '%s' not found, object contains only %s"
113 Just val -> fromKeyValue k val
115 -- | Reads the value of an optional key in a JSON object. Missing
116 -- keys, or keys that have a \'null\' value, will be returned as
117 -- 'Nothing', otherwise we attempt deserialisation and return a 'Just'
119 maybeFromObj :: (J.JSON a, Monad m) =>
120 JSRecord -> String -> m (Maybe a)
123 Nothing -> return Nothing
124 -- a optional key with value JSNull is the same as missing, since
125 -- we can't convert it meaningfully anyway to a Haskell type, and
126 -- the Python code can emit 'null' for optional values (depending
127 -- on usage), and finally our encoding rules treat 'null' values
129 Just J.JSNull -> return Nothing
130 Just val -> liftM Just (fromKeyValue k val)
132 -- | Reads the value of a key in a JSON object with a default if
133 -- missing. Note that both missing keys and keys with value \'null\'
134 -- will case the default value to be returned.
135 fromObjWithDefault :: (J.JSON a, Monad m) =>
136 JSRecord -> String -> a -> m a
137 fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
139 -- | Reads a JValue, that originated from an object key.
140 fromKeyValue :: (J.JSON a, Monad m)
141 => String -- ^ The key name
142 -> J.JSValue -- ^ The value to read
145 fromJResult (printf "key '%s'" k) (J.readJSON val)
147 -- | Small wrapper over readJSON.
148 fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
151 J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++
155 -- | Helper function that returns Null or first element of the list.
156 jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
157 jsonHead [] _ = J.JSNull
158 jsonHead (x:_) f = J.showJSON $ f x
160 -- | Helper for extracting Maybe values from a possibly empty list.
161 getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
162 getMaybeJsonHead [] _ = J.JSNull
163 getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
165 -- | Converts a JSON value into a JSON object.
166 asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
167 asJSObject (J.JSObject a) = return a
168 asJSObject _ = fail "not an object"
170 -- | Coneverts a list of JSON values into a list of JSON objects.
171 asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
172 asObjectList = mapM asJSObject
174 -- | Try to extract a key from a object with better error reporting
176 tryFromObj :: (J.JSON a) =>
177 String -- ^ Textual "owner" in error messages
178 -> JSRecord -- ^ The object array
179 -> String -- ^ The desired key from the object
181 tryFromObj t o = annotateResult t . fromObj o
183 -- | Ensure a given JSValue is actually a JSArray.
184 toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
185 toArray (J.JSArray arr) = return arr
187 fail $ "Invalid input, expected array but got " ++ show (pp_value o)
189 -- | Creates a Maybe JSField. If the value string is Nothing, the JSField
190 -- will be Nothing as well.
191 optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
192 optionalJSField name (Just value) = Just (name, J.showJSON value)
193 optionalJSField _ Nothing = Nothing
195 -- | Creates an object with all the non-Nothing fields of the given list.
196 optFieldsToObj :: [Maybe JSField] -> J.JSValue
197 optFieldsToObj = J.makeObj . catMaybes
199 -- * Container type (special type for JSON serialisation)
201 -- | Class of types that can be converted from Strings. This is
202 -- similar to the 'Read' class, but it's using a different
203 -- serialisation format, so we have to define a separate class. Mostly
204 -- useful for custom key types in JSON dictionaries, which have to be
205 -- backed by strings.
206 class HasStringRepr a where
207 fromStringRepr :: (Monad m) => String -> m a
208 toStringRepr :: a -> String
210 -- | Trivial instance 'HasStringRepr' for 'String'.
211 instance HasStringRepr String where
212 fromStringRepr = return
215 -- | The container type, a wrapper over Data.Map
216 newtype GenericContainer a b =
217 GenericContainer { fromContainer :: Map.Map a b }
220 instance (NFData a, NFData b) => NFData (GenericContainer a b) where
221 rnf = rnf . Map.toList . fromContainer
223 -- | Type alias for string keys.
224 type Container = GenericContainer String
226 -- | Container loader.
227 readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
228 J.JSObject J.JSValue -> m (GenericContainer a b)
229 readContainer obj = do
230 let kjvlist = J.fromJSObject obj
231 kalist <- mapM (\(k, v) -> do
232 k' <- fromStringRepr k
233 v' <- fromKeyValue k v
234 return (k', v')) kjvlist
235 return $ GenericContainer (Map.fromList kalist)
237 {-# ANN showContainer "HLint: ignore Use ***" #-}
238 -- | Container dumper.
239 showContainer :: (HasStringRepr a, J.JSON b) =>
240 GenericContainer a b -> J.JSValue
242 J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) .
243 Map.toList . fromContainer
245 instance (HasStringRepr a, Ord a, J.JSON b) =>
246 J.JSON (GenericContainer a b) where
247 showJSON = showContainer
248 readJSON (J.JSObject o) = readContainer o
249 readJSON v = fail $ "Failed to load container, expected object but got "