| Copyright | (c) 2015-2016 Brendan Hay <brendan.g.hay@gmail.com> |
|---|---|
| License | Mozilla Public License, v. 2.0. |
| Maintainer | Brendan Hay <brendan.g.hay@gmail.com> |
| Stability | provisional |
| Portability | non-portable (GHC extensions) |
| Safe Haskell | None |
| Language | Haskell2010 |
Network.Google.Data.JSON
Contents
Description
Synopsis
- type JSONValue = Value
- newtype Textual a = Textual a
- parseJSONObject :: FromJSON a => HashMap Text Value -> Parser a
- parseJSONText :: FromHttpApiData a => String -> Value -> Parser a
- toJSONText :: ToHttpApiData a => a -> Value
- class FromJSON a where
- class ToJSON a where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- withObject :: String -> (Object -> Parser a) -> Value -> Parser a
- emptyObject :: Value
- object :: [Pair] -> Value
- (.=) :: (KeyValue kv, ToJSON v) => Text -> v -> kv
- (.:) :: FromJSON a => Object -> Text -> Parser a
- (.:?) :: FromJSON a => Object -> Text -> Parser (Maybe a)
- (.!=) :: Parser (Maybe a) -> a -> Parser a
Documentation
Constructors
| Textual a |
Instances
| Eq a => Eq (Textual a) Source # | |
| Fractional a => Fractional (Textual a) Source # | |
| Data a => Data (Textual a) Source # | |
Defined in Network.Google.Data.JSON Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Textual a -> c (Textual a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Textual a) # toConstr :: Textual a -> Constr # dataTypeOf :: Textual a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Textual a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Textual a)) # gmapT :: (forall b. Data b => b -> b) -> Textual a -> Textual a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Textual a -> r # gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Textual a -> r # gmapQ :: (forall d. Data d => d -> u) -> Textual a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Textual a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Textual a -> m (Textual a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Textual a -> m (Textual a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Textual a -> m (Textual a) # | |
| Num a => Num (Textual a) Source # | |
Defined in Network.Google.Data.JSON | |
| Ord a => Ord (Textual a) Source # | |
| Read a => Read (Textual a) Source # | |
| Show a => Show (Textual a) Source # | |
| ToHttpApiData a => ToJSON (Textual a) Source # | |
Defined in Network.Google.Data.JSON | |
| (FromJSON a, FromHttpApiData a) => FromJSON (Textual a) Source # | |
| ToHttpApiData a => ToHttpApiData (Textual a) Source # | |
Defined in Network.Google.Data.JSON Methods toUrlPiece :: Textual a -> Text # toEncodedUrlPiece :: Textual a -> Builder # toHeader :: Textual a -> ByteString # toQueryParam :: Textual a -> Text # | |
| FromHttpApiData a => FromHttpApiData (Textual a) Source # | |
Defined in Network.Google.Data.JSON Methods parseUrlPiece :: Text -> Either Text (Textual a) # parseHeader :: ByteString -> Either Text (Textual a) # | |
parseJSONText :: FromHttpApiData a => String -> Value -> Parser a Source #
toJSONText :: ToHttpApiData a => a -> Value Source #
Re-exports
A type that can be converted from JSON, with the possibility of failure.
In many cases, you can get the compiler to generate parsing code for you (see below). To begin, let's cover writing an instance by hand.
There are various reasons a conversion could fail. For example, an
Object could be missing a required key, an Array could be of
the wrong size, or a value could be of an incompatible type.
The basic ways to signal a failed conversion are as follows:
emptyandmzerowork, but are terse and uninformative;failyields a custom error message;typeMismatchproduces an informative message for cases when the value encountered is not of the expected type.
An example type and instance using typeMismatch:
-- Allow ourselves to writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSONCoord whereparseJSON(Objectv) = Coord<$>v.:"x"<*>v.:"y" -- We do not expect a non-Objectvalue here. -- We could usemzeroto fail, buttypeMismatch-- gives a much more informative error message.parseJSONinvalid =typeMismatch"Coord" invalid
For this common case of only being concerned with a single
type of JSON value, the functions withObject, withNumber, etc.
are provided. Their use is to be preferred when possible, since
they are more terse. Using withObject, we can rewrite the above instance
(assuming the same language extension and data type) as:
instanceFromJSONCoord whereparseJSON=withObject"Coord" $ \v -> Coord<$>v.:"x"<*>v.:"y"
Instead of manually writing your FromJSON instance, there are two options
to do it automatically:
- Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
- The compiler can provide a default generic implementation for
parseJSON.
To use the second, simply add a deriving clause to your
datatype and declare a GenericFromJSON instance for your datatype without giving
a definition for parseJSON.
For example, the previous example can be simplified to just:
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
data Coord = Coord { x :: Double, y :: Double } deriving Generic
instance FromJSON Coord
The default implementation will be equivalent to
parseJSON = ; If you need different
options, you can customize the generic decoding by defining:genericParseJSON defaultOptions
customOptions =defaultOptions{fieldLabelModifier=maptoUpper} instanceFromJSONCoord whereparseJSON=genericParseJSONcustomOptions
Minimal complete definition
Nothing
Instances
A type that can be converted to JSON.
Instances in general must specify toJSON and should (but don't need
to) specify toEncoding.
An example type and instance:
-- Allow ourselves to writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSONCoord wheretoJSON(Coord x y) =object["x".=x, "y".=y]toEncoding(Coord x y) =pairs("x".=x<>"y".=y)
Instead of manually writing your ToJSON instance, there are two options
to do it automatically:
- Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
- The compiler can provide a default generic implementation for
toJSON.
To use the second, simply add a deriving clause to your
datatype and declare a GenericToJSON instance. If you require nothing other than
defaultOptions, it is sufficient to write (and this is the only
alternative where the default toJSON implementation is sufficient):
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
data Coord = Coord { x :: Double, y :: Double } deriving Generic
instance ToJSON Coord where
toEncoding = genericToEncoding defaultOptions
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions{fieldLabelModifier=maptoUpper} instanceToJSONCoord wheretoJSON=genericToJSONcustomOptionstoEncoding=genericToEncodingcustomOptions
Previous versions of this library only had the toJSON method. Adding
toEncoding had two reasons:
- toEncoding is more efficient for the common case that the output of
toJSONis directly serialized to aByteString. Further, expressing either method in terms of the other would be non-optimal. - The choice of defaults allows a smooth transition for existing users:
Existing instances that do not define
toEncodingstill compile and have the correct semantics. This is ensured by making the default implementation oftoEncodingusetoJSON. This produces correct results, but since it performs an intermediate conversion to aValue, it will be less efficient than directly emitting anEncoding. (this also means that specifying nothing more thaninstance ToJSON Coordwould be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncodingin new instances.)
Minimal complete definition
Nothing
Methods
Convert a Haskell value to a JSON-friendly intermediate type.
toEncoding :: a -> Encoding #
Encode a Haskell value as JSON.
The default implementation of this method creates an
intermediate Value using toJSON. This provides
source-level compatibility for people upgrading from older
versions of this library, but obviously offers no performance
advantage.
To benefit from direct encoding, you must provide an
implementation for this method. The easiest way to do so is by
having your types implement Generic using the DeriveGeneric
extension, and then have GHC generate a method body as follows.
instanceToJSONCoord wheretoEncoding=genericToEncodingdefaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
Instances
withObject :: String -> (Object -> Parser a) -> Value -> Parser a #
applies withObject expected f valuef to the Object when value
is an Object and fails using otherwise.typeMismatch expected
emptyObject :: Value #
The empty object.
(.:) :: FromJSON a => Object -> Text -> Parser a #
Retrieve the value associated with the given key of an Object.
The result is empty if the key is not present or the value cannot
be converted to the desired type.
This accessor is appropriate if the key and value must be present
in an object for it to be valid. If the key and value are
optional, use .:? instead.
(.:?) :: FromJSON a => Object -> Text -> Parser (Maybe a) #
Retrieve the value associated with the given key of an Object. The
result is Nothing if the key is not present or if its value is Null,
or empty if the value cannot be converted to the desired type.
This accessor is most useful if the key and value can be absent
from an object without affecting its validity. If the key and
value are mandatory, use .: instead.
(.!=) :: Parser (Maybe a) -> a -> Parser a #
Helper for use in combination with .:? to provide default
values for optional JSON object fields.
This combinator is most useful if the key and value can be absent
from an object without affecting its validity and we know a default
value to assign in that case. If the key and value are mandatory,
use .: instead.
Example usage:
v1 <- o.:?"opt_field_with_dfl" .!= "default_val" v2 <- o.:"mandatory_field" v3 <- o.:?"opt_field2"