| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Json.Encode
Synopsis
- type Array = Vector Value
- emptyArray :: Value
- type Object = HashMap Text Value
- emptyObject :: Value
- class ToJSON a where
- gtoJson :: (Generic a, GtoJson (Rep a), ConNames (Rep a), GIsEnum (Rep a)) => a -> Value
- class ToJSONKey a where
- data ToJSONKeyFunction a
- = ToJSONKeyText !(a -> Text) !(a -> Encoding' Text)
- | ToJSONKeyValue !(a -> Value) !(a -> Encoding)
- encode :: ToJSON a => a -> ByteString
- encodeToLazyText :: ToJSON a => a -> Text
- encodePretty :: ToJSON a => a -> ByteString
- class KeyValue kv
- (.=) :: (KeyValue kv, ToJSON v) => Text -> v -> kv
- object :: [Pair] -> Value
- type Encoding = Encoding' Value
- data Encoding' tag
- encodingToLazyByteString :: Encoding' a -> ByteString
- data Series
- pairs :: Series -> Encoding
- pair :: Text -> Encoding -> Series
- pair' :: Encoding' Text -> Encoding -> Series
- foldable :: (Foldable t, ToJSON a) => t a -> Encoding
- emptyArray_ :: Encoding
- emptyObject_ :: Encoding
- text :: Text -> Encoding' a
- lazyText :: Text -> Encoding' a
- string :: String -> Encoding' a
- list :: (a -> Encoding) -> [a] -> Encoding
- dict :: (k -> Encoding' Text) -> (v -> Encoding) -> (forall a. (k -> v -> a -> a) -> a -> m -> a) -> m -> Encoding
- null_ :: Encoding
- bool :: Bool -> Encoding
- int8 :: Int8 -> Encoding
- int16 :: Int16 -> Encoding
- int32 :: Int32 -> Encoding
- int64 :: Int64 -> Encoding
- int :: Int -> Encoding
- word8 :: Word8 -> Encoding
- word16 :: Word16 -> Encoding
- word32 :: Word32 -> Encoding
- word64 :: Word64 -> Encoding
- word :: Word -> Encoding
- integer :: Integer -> Encoding
- float :: Float -> Encoding
- double :: Double -> Encoding
- scientific :: Scientific -> Encoding
- int8Text :: Int8 -> Encoding' a
- int16Text :: Int16 -> Encoding' a
- int32Text :: Int32 -> Encoding' a
- int64Text :: Int64 -> Encoding' a
- intText :: Int -> Encoding' a
- word8Text :: Word8 -> Encoding' a
- word16Text :: Word16 -> Encoding' a
- word32Text :: Word32 -> Encoding' a
- word64Text :: Word64 -> Encoding' a
- wordText :: Word -> Encoding' a
- integerText :: Integer -> Encoding' a
- floatText :: Float -> Encoding' a
- doubleText :: Double -> Encoding' a
- scientificText :: Scientific -> Encoding' a
- day :: Day -> Encoding' a
- localTime :: LocalTime -> Encoding' a
- utcTime :: UTCTime -> Encoding' a
- timeOfDay :: TimeOfDay -> Encoding' a
- zonedTime :: ZonedTime -> Encoding' a
- value :: Value -> Encoding
- aesonQQ :: QuasiQuoter
- newtype DotNetTime = DotNetTime {}
- module Json
Encoding
emptyArray :: Value #
The empty array.
emptyObject :: Value #
The empty object.
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 to 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.)
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
Typeclass for types that can be used as the key of a map-like container
(like Map or HashMap). For example, since Text has a ToJSONKey
instance and Char has a ToJSON instance, we can encode a value of
type Map Text Char:
>>>LBC8.putStrLn $ encode $ Map.fromList [("foo" :: Text, 'a')]{"foo":"a"}
Since Int also has a ToJSONKey instance, we can similarly write:
>>>LBC8.putStrLn $ encode $ Map.fromList [(5 :: Int, 'a')]{"5":"a"}
JSON documents only accept strings as object keys. For any type
from base that has a natural textual representation, it can be
expected that its ToJSONKey instance will choose that representation.
For data types that lack a natural textual representation, an alternative is provided. The map-like container is represented as a JSON array instead of a JSON object. Each value in the array is an array with exactly two values. The first is the key and the second is the value.
For example, values of type '[Text]' cannot be encoded to a
string, so a Map with keys of type '[Text]' is encoded as follows:
>>>LBC8.putStrLn $ encode $ Map.fromList [(["foo","bar","baz" :: Text], 'a')][[["foo","bar","baz"],"a"]]
The default implementation of ToJSONKey chooses this method of
encoding a key, using the ToJSON instance of the type.
To use your own data type as the key in a map, all that is needed
is to write a ToJSONKey (and possibly a FromJSONKey) instance
for it. If the type cannot be trivially converted to and from Text,
it is recommended that ToJSONKeyValue is used. Since the default
implementations of the typeclass methods can build this from a
ToJSON instance, there is nothing that needs to be written:
data Foo = Foo { fooAge :: Int, fooName :: Text }
deriving (Eq,Ord,Generic)
instance ToJSON Foo
instance ToJSONKey FooThat's it. We can now write:
>>>let m = Map.fromList [(Foo 4 "bar",'a'),(Foo 6 "arg",'b')]>>>LBC8.putStrLn $ encode m[[{"fooName":"bar","fooAge":4},"a"],[{"fooName":"arg","fooAge":6},"b"]]
The next case to consider is if we have a type that is a
newtype wrapper around Text. The recommended approach is to use
generalized newtype deriving:
newtype RecordId = RecordId { getRecordId :: Text}
deriving (Eq,Ord,ToJSONKey)Then we may write:
>>>LBC8.putStrLn $ encode $ Map.fromList [(RecordId "abc",'a')]{"abc":"a"}
Simple sum types are a final case worth considering. Suppose we have:
data Color = Red | Green | Blue deriving (Show,Read,Eq,Ord)
It is possible to get the ToJSONKey instance for free as we did
with Foo. However, in this case, we have a natural way to go to
and from Text that does not require any escape sequences. So, in
this example, ToJSONKeyText will be used instead of ToJSONKeyValue.
The Show instance can be used to help write ToJSONKey:
instance ToJSONKey Color where
toJSONKey = ToJSONKeyText f g
where f = Text.pack . show
g = text . Text.pack . show
-- text function is from Data.Aeson.EncodingThe situation of needing to turning function a -> Text into
a ToJSONKeyFunction is common enough that a special combinator
is provided for it. The above instance can be rewritten as:
instance ToJSONKey Color where toJSONKey = toJSONKeyText (Text.pack . show)
The performance of the above instance can be improved by
not using String as an intermediate step when converting to
Text. One option for improving performance would be to use
template haskell machinery from the text-show package. However,
even with the approach, the Encoding (a wrapper around a bytestring
builder) is generated by encoding the Text to a ByteString,
an intermediate step that could be avoided. The fastest possible
implementation would be:
-- Assuming that OverloadedStrings is enabled
instance ToJSONKey Color where
toJSONKey = ToJSONKeyText f g
where f x = case x of {Red -> "Red";Green ->"Green";Blue -> "Blue"}
g x = case x of {Red -> text "Red";Green -> text "Green";Blue -> text "Blue"}
-- text function is from Data.Aeson.EncodingThis works because GHC can lift the encoded values out of the case statements, which means that they are only evaluated once. This approach should only be used when there is a serious need to maximize performance.
Methods
toJSONKey :: ToJSONKeyFunction a #
Strategy for rendering the key for a map-like container.
toJSONKeyList :: ToJSONKeyFunction [a] #
Instances
data ToJSONKeyFunction a #
Constructors
| ToJSONKeyText !(a -> Text) !(a -> Encoding' Text) | key is encoded to string, produces object |
| ToJSONKeyValue !(a -> Value) !(a -> Encoding) | key is encoded to value, produces array |
encode :: ToJSON a => a -> ByteString #
Efficiently serialize a JSON value as a lazy ByteString.
This is implemented in terms of the ToJSON class's toEncoding method.
encodeToLazyText :: ToJSON a => a -> Text #
Encode a JSON Value to a Data.Text.Lazy
Note: uses toEncoding
encodePretty :: ToJSON a => a -> ByteString #
A key-value pair for encoding a JSON object.
Minimal complete definition
Direct encoding
An encoding of a JSON value.
tag represents which kind of JSON the Encoding is encoding to,
we reuse Text and Value as tags here.
Instances
| FromString Encoding | |
Defined in Data.Aeson.Types.ToJSON Methods fromString :: String -> Encoding | |
| GToJSON Encoding arity (U1 :: * -> *) | |
| ToJSON1 f => GToJSON Encoding One (Rec1 f) | |
| ToJSON a => GToJSON Encoding arity (K1 i a :: * -> *) | |
| (EncodeProduct arity a, EncodeProduct arity b) => GToJSON Encoding arity (a :*: b) | |
| (ToJSON1 f, GToJSON Encoding One g) => GToJSON Encoding One (f :.: g) | |
| Eq (Encoding' a) | |
| Ord (Encoding' a) | |
Defined in Data.Aeson.Encoding.Internal | |
| Show (Encoding' a) | |
| a ~ Value => FromPairs (Encoding' a) Series | |
Defined in Data.Aeson.Types.ToJSON | |
| (GToJSON Encoding arity a, ConsToJSON Encoding arity a, Constructor c) => SumToJSON' TwoElemArray Encoding arity (C1 c a) | |
Defined in Data.Aeson.Types.ToJSON | |
encodingToLazyByteString :: Encoding' a -> ByteString #
A series of values that, when encoded, should be separated by
commas. Since 0.11.0.0, the .= operator is overloaded to create
either (Text, Value) or Series. You can use Series when
encoding directly to a bytestring builder as in the following
example:
toEncoding (Person name age) = pairs ("name" .= name <> "age" .= age)emptyArray_ :: Encoding #
Arguments
| :: (k -> Encoding' Text) | key encoding |
| -> (v -> Encoding) | value encoding |
| -> (forall a. (k -> v -> a -> a) -> a -> m -> a) |
|
| -> m | container |
| -> Encoding |
Encode as JSON object
scientific :: Scientific -> Encoding #
word16Text :: Word16 -> Encoding' a #
word32Text :: Word32 -> Encoding' a #
word64Text :: Word64 -> Encoding' a #
integerText :: Integer -> Encoding' a #
doubleText :: Double -> Encoding' a #
scientificText :: Scientific -> Encoding' a #
Quasi-quotation
aesonQQ :: QuasiQuoter #
Newtypes
newtype DotNetTime #
A newtype wrapper for UTCTime that uses the same non-standard
serialization format as Microsoft .NET, whose
System.DateTime
type is by default serialized to JSON as in the following example:
/Date(1302547608878)/
The number represents milliseconds since the Unix epoch.
Constructors
| DotNetTime | |
Fields
| |
Instances
Re-exports
module Json