on db520e4 help sign in
64 lines 1.8 kB history raw
1{-# LANGUAGE DeriveDataTypeable #-}
2{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE ScopedTypeVariables #-}
5-- |
6-- Module : Network.Google.Data.JSON
7-- Copyright : (c) 2015 Brendan Hay <brendan.g.hay@gmail.com>
8-- License : Mozilla Public License, v. 2.0.
9-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
10-- Stability : provisional
11-- Portability : non-portable (GHC extensions)
12--
13module Network.Google.Data.JSON
14 ( JSONValue
15 , Textual (..)
16 , parseJSONObject
17 , parseJSONText
18 , toJSONText
20 -- * Re-exports
21 , FromJSON (..)
22 , ToJSON (..)
24 , withObject
25 , emptyObject
26 , object
28 , (.=)
29 , (.:)
30 , (.:?)
31 , (.!=)
32 ) where
34import Data.Aeson
35import Data.Aeson.Types
36import Data.Data
37import Data.HashMap.Strict (HashMap)
38import Data.Text (Text)
39import qualified Data.Text as Text
40import Servant.API
42type JSONValue = Value
44newtype Textual a = Textual a
45 deriving (Eq, Ord, Read, Show, Num, Fractional, Data, Typeable, FromText, ToText)
47instance (FromJSON a, FromText a) => FromJSON (Textual a) where
48 parseJSON (String s) =
49 case fromText s of
50 Just x -> pure (Textual x)
51 Nothing -> fail $ "Failed to parse value from " ++ Text.unpack s
52 parseJSON o = Textual <$> parseJSON o
54instance ToText a => ToJSON (Textual a) where
55 toJSON (Textual x) = String (toText x)
57parseJSONObject :: FromJSON a => HashMap Text Value -> Parser a
58parseJSONObject = parseJSON . Object
60parseJSONText :: FromText a => String -> Value -> Parser a
61parseJSONText n = withText n (maybe (fail n) pure . fromText)
63toJSONText :: ToText a => a -> Value
64toJSONText = String . toText