root / src / Ganeti / JSON.hs @ a4f35477
History | View | Annotate | Download (9.3 kB)
1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} |
---|---|
2 |
{-# OPTIONS_GHC -fno-warn-orphans #-} |
3 |
|
4 |
{-| JSON utility functions. -} |
5 |
|
6 |
{- |
7 |
|
8 |
Copyright (C) 2009, 2010, 2011, 2012 Google Inc. |
9 |
|
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. |
14 |
|
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. |
19 |
|
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 |
23 |
02110-1301, USA. |
24 |
|
25 |
-} |
26 |
|
27 |
module Ganeti.JSON |
28 |
( fromJResult |
29 |
, readEitherString |
30 |
, JSRecord |
31 |
, loadJSArray |
32 |
, fromObj |
33 |
, maybeFromObj |
34 |
, fromObjWithDefault |
35 |
, fromKeyValue |
36 |
, fromJVal |
37 |
, jsonHead |
38 |
, getMaybeJsonHead |
39 |
, asJSObject |
40 |
, asObjectList |
41 |
, tryFromObj |
42 |
, tryArrayMaybeFromObj |
43 |
, toArray |
44 |
, optionalJSField |
45 |
, optFieldsToObj |
46 |
, HasStringRepr(..) |
47 |
, GenericContainer(..) |
48 |
, Container |
49 |
) |
50 |
where |
51 |
|
52 |
import Control.DeepSeq |
53 |
import Control.Monad (liftM) |
54 |
import Data.Maybe (fromMaybe, catMaybes) |
55 |
import qualified Data.Map as Map |
56 |
import Text.Printf (printf) |
57 |
|
58 |
import qualified Text.JSON as J |
59 |
import Text.JSON.Pretty (pp_value) |
60 |
|
61 |
-- Note: this module should not import any Ganeti-specific modules |
62 |
-- beside BasicTypes, since it's used in THH which is used itself to |
63 |
-- build many other modules. |
64 |
|
65 |
import Ganeti.BasicTypes |
66 |
|
67 |
-- * JSON-related functions |
68 |
|
69 |
instance NFData J.JSValue where |
70 |
rnf J.JSNull = () |
71 |
rnf (J.JSBool b) = rnf b |
72 |
rnf (J.JSRational b r) = rnf b `seq` rnf r |
73 |
rnf (J.JSString s) = rnf $ J.fromJSString s |
74 |
rnf (J.JSArray a) = rnf a |
75 |
rnf (J.JSObject o) = rnf o |
76 |
|
77 |
instance (NFData a) => NFData (J.JSObject a) where |
78 |
rnf = rnf . J.fromJSObject |
79 |
|
80 |
-- | A type alias for a field of a JSRecord. |
81 |
type JSField = (String, J.JSValue) |
82 |
|
83 |
-- | A type alias for the list-based representation of J.JSObject. |
84 |
type JSRecord = [JSField] |
85 |
|
86 |
-- | Converts a JSON Result into a monadic value. |
87 |
fromJResult :: Monad m => String -> J.Result a -> m a |
88 |
fromJResult s (J.Error x) = fail (s ++ ": " ++ x) |
89 |
fromJResult _ (J.Ok x) = return x |
90 |
|
91 |
-- | Tries to read a string from a JSON value. |
92 |
-- |
93 |
-- In case the value was not a string, we fail the read (in the |
94 |
-- context of the current monad. |
95 |
readEitherString :: (Monad m) => J.JSValue -> m String |
96 |
readEitherString v = |
97 |
case v of |
98 |
J.JSString s -> return $ J.fromJSString s |
99 |
_ -> fail "Wrong JSON type" |
100 |
|
101 |
-- | Converts a JSON message into an array of JSON objects. |
102 |
loadJSArray :: (Monad m) |
103 |
=> String -- ^ Operation description (for error reporting) |
104 |
-> String -- ^ Input message |
105 |
-> m [J.JSObject J.JSValue] |
106 |
loadJSArray s = fromJResult s . J.decodeStrict |
107 |
|
108 |
-- | Helper function for missing-key errors |
109 |
buildNoKeyError :: JSRecord -> String -> String |
110 |
buildNoKeyError o k = |
111 |
printf "key '%s' not found, object contains only %s" k (show (map fst o)) |
112 |
|
113 |
-- | Reads the value of a key in a JSON object. |
114 |
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a |
115 |
fromObj o k = |
116 |
case lookup k o of |
117 |
Nothing -> fail $ buildNoKeyError o k |
118 |
Just val -> fromKeyValue k val |
119 |
|
120 |
-- | Reads the value of an optional key in a JSON object. Missing |
121 |
-- keys, or keys that have a \'null\' value, will be returned as |
122 |
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just' |
123 |
-- value. |
124 |
maybeFromObj :: (J.JSON a, Monad m) => |
125 |
JSRecord -> String -> m (Maybe a) |
126 |
maybeFromObj o k = |
127 |
case lookup k o of |
128 |
Nothing -> return Nothing |
129 |
-- a optional key with value JSNull is the same as missing, since |
130 |
-- we can't convert it meaningfully anyway to a Haskell type, and |
131 |
-- the Python code can emit 'null' for optional values (depending |
132 |
-- on usage), and finally our encoding rules treat 'null' values |
133 |
-- as 'missing' |
134 |
Just J.JSNull -> return Nothing |
135 |
Just val -> liftM Just (fromKeyValue k val) |
136 |
|
137 |
-- | Reads the value of a key in a JSON object with a default if |
138 |
-- missing. Note that both missing keys and keys with value \'null\' |
139 |
-- will case the default value to be returned. |
140 |
fromObjWithDefault :: (J.JSON a, Monad m) => |
141 |
JSRecord -> String -> a -> m a |
142 |
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k |
143 |
|
144 |
-- | Reads an array of optional items |
145 |
arrayMaybeFromObj :: (J.JSON a, Monad m) => |
146 |
JSRecord -> String -> m [Maybe a] |
147 |
arrayMaybeFromObj o k = |
148 |
case lookup k o of |
149 |
Just (J.JSArray xs) -> mapM parse xs |
150 |
where |
151 |
parse J.JSNull = return Nothing |
152 |
parse x = liftM Just $ fromJVal x |
153 |
_ -> fail $ buildNoKeyError o k |
154 |
|
155 |
-- | Wrapper for arrayMaybeFromObj with better diagnostic |
156 |
tryArrayMaybeFromObj :: (J.JSON a) |
157 |
=> String -- ^ Textual "owner" in error messages |
158 |
-> JSRecord -- ^ The object array |
159 |
-> String -- ^ The desired key from the object |
160 |
-> Result [Maybe a] |
161 |
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o |
162 |
|
163 |
-- | Reads a JValue, that originated from an object key. |
164 |
fromKeyValue :: (J.JSON a, Monad m) |
165 |
=> String -- ^ The key name |
166 |
-> J.JSValue -- ^ The value to read |
167 |
-> m a |
168 |
fromKeyValue k val = |
169 |
fromJResult (printf "key '%s'" k) (J.readJSON val) |
170 |
|
171 |
-- | Small wrapper over readJSON. |
172 |
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a |
173 |
fromJVal v = |
174 |
case J.readJSON v of |
175 |
J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++ |
176 |
"', error: " ++ s) |
177 |
J.Ok x -> return x |
178 |
|
179 |
-- | Helper function that returns Null or first element of the list. |
180 |
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue |
181 |
jsonHead [] _ = J.JSNull |
182 |
jsonHead (x:_) f = J.showJSON $ f x |
183 |
|
184 |
-- | Helper for extracting Maybe values from a possibly empty list. |
185 |
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue |
186 |
getMaybeJsonHead [] _ = J.JSNull |
187 |
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x) |
188 |
|
189 |
-- | Converts a JSON value into a JSON object. |
190 |
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue) |
191 |
asJSObject (J.JSObject a) = return a |
192 |
asJSObject _ = fail "not an object" |
193 |
|
194 |
-- | Coneverts a list of JSON values into a list of JSON objects. |
195 |
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue] |
196 |
asObjectList = mapM asJSObject |
197 |
|
198 |
-- | Try to extract a key from an object with better error reporting |
199 |
-- than fromObj. |
200 |
tryFromObj :: (J.JSON a) => |
201 |
String -- ^ Textual "owner" in error messages |
202 |
-> JSRecord -- ^ The object array |
203 |
-> String -- ^ The desired key from the object |
204 |
-> Result a |
205 |
tryFromObj t o = annotateResult t . fromObj o |
206 |
|
207 |
-- | Ensure a given JSValue is actually a JSArray. |
208 |
toArray :: (Monad m) => J.JSValue -> m [J.JSValue] |
209 |
toArray (J.JSArray arr) = return arr |
210 |
toArray o = |
211 |
fail $ "Invalid input, expected array but got " ++ show (pp_value o) |
212 |
|
213 |
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField |
214 |
-- will be Nothing as well. |
215 |
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField |
216 |
optionalJSField name (Just value) = Just (name, J.showJSON value) |
217 |
optionalJSField _ Nothing = Nothing |
218 |
|
219 |
-- | Creates an object with all the non-Nothing fields of the given list. |
220 |
optFieldsToObj :: [Maybe JSField] -> J.JSValue |
221 |
optFieldsToObj = J.makeObj . catMaybes |
222 |
|
223 |
-- * Container type (special type for JSON serialisation) |
224 |
|
225 |
-- | Class of types that can be converted from Strings. This is |
226 |
-- similar to the 'Read' class, but it's using a different |
227 |
-- serialisation format, so we have to define a separate class. Mostly |
228 |
-- useful for custom key types in JSON dictionaries, which have to be |
229 |
-- backed by strings. |
230 |
class HasStringRepr a where |
231 |
fromStringRepr :: (Monad m) => String -> m a |
232 |
toStringRepr :: a -> String |
233 |
|
234 |
-- | Trivial instance 'HasStringRepr' for 'String'. |
235 |
instance HasStringRepr String where |
236 |
fromStringRepr = return |
237 |
toStringRepr = id |
238 |
|
239 |
-- | The container type, a wrapper over Data.Map |
240 |
newtype GenericContainer a b = |
241 |
GenericContainer { fromContainer :: Map.Map a b } |
242 |
deriving (Show, Eq) |
243 |
|
244 |
instance (NFData a, NFData b) => NFData (GenericContainer a b) where |
245 |
rnf = rnf . Map.toList . fromContainer |
246 |
|
247 |
-- | Type alias for string keys. |
248 |
type Container = GenericContainer String |
249 |
|
250 |
-- | Container loader. |
251 |
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) => |
252 |
J.JSObject J.JSValue -> m (GenericContainer a b) |
253 |
readContainer obj = do |
254 |
let kjvlist = J.fromJSObject obj |
255 |
kalist <- mapM (\(k, v) -> do |
256 |
k' <- fromStringRepr k |
257 |
v' <- fromKeyValue k v |
258 |
return (k', v')) kjvlist |
259 |
return $ GenericContainer (Map.fromList kalist) |
260 |
|
261 |
{-# ANN showContainer "HLint: ignore Use ***" #-} |
262 |
-- | Container dumper. |
263 |
showContainer :: (HasStringRepr a, J.JSON b) => |
264 |
GenericContainer a b -> J.JSValue |
265 |
showContainer = |
266 |
J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) . |
267 |
Map.toList . fromContainer |
268 |
|
269 |
instance (HasStringRepr a, Ord a, J.JSON b) => |
270 |
J.JSON (GenericContainer a b) where |
271 |
showJSON = showContainer |
272 |
readJSON (J.JSObject o) = readContainer o |
273 |
readJSON v = fail $ "Failed to load container, expected object but got " |
274 |
++ show (pp_value v) |