3-- Copyright: (c) 2011-2016 Bryan O'Sullivan
4-- (c) 2011 MailRank, Inc.
6-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
7-- Stability: experimental
8-- Portability: portable
10-- Types and functions for working efficiently with JSON data.
12-- (A note on naming: in Greek mythology, Aeson was the father of Jason.)
16 -- * How to use this library
19 -- ** Writing instances by hand
22 -- ** Working with the AST
25 -- ** Decoding to a Haskell value
28 -- ** Decoding a mixed-type object
31 -- * Encoding and decoding
32 -- $encoding_and_decoding
41 -- ** Variants for strict bytestrings
52 -- * Convenience types
62 , ToJSONKeyFunction(..)
64 , FromJSONKeyFunction(..)
65 -- ** Liftings to unary and binary type constructors
76 -- ** Generic JSON classes and options
87 , genericLiftToEncoding
89 , genericLiftParseJSON
92 -- * Inspecting @'Value's@
99 -- * Constructors and accessors
116import Data.Aeson.Types.FromJSON (ifromJSON)
117import Data.Aeson.Encoding (encodingToLazyByteString)
118import Data.Aeson.Parser.Internal (decodeWith, decodeStrictWith, eitherDecodeWith, eitherDecodeStrictWith, jsonEOF, json, jsonEOF', json')
119import Data.Aeson.Types
120import Data.Aeson.Types.Internal (JSONPath, formatError)
121import qualified Data.ByteString as B
122import qualified Data.ByteString.Lazy as L
124-- | Efficiently serialize a JSON value as a lazy 'L.ByteString'.
126-- This is implemented in terms of the 'ToJSON' class's 'toEncoding' method.
127encode :: (ToJSON a) => a -> L.ByteString
128encode = encodingToLazyByteString . toEncoding
130-- | Efficiently deserialize a JSON value from a lazy 'L.ByteString'.
131-- If this fails due to incomplete or invalid input, 'Nothing' is
134-- The input must consist solely of a JSON document, with no trailing
135-- data except for whitespace.
137-- This function parses immediately, but defers conversion. See
138-- 'json' for details.
139decode :: (FromJSON a) => L.ByteString -> Maybe a
140decode = decodeWith jsonEOF fromJSON
143-- | Efficiently deserialize a JSON value from a strict 'B.ByteString'.
144-- If this fails due to incomplete or invalid input, 'Nothing' is
147-- The input must consist solely of a JSON document, with no trailing
148-- data except for whitespace.
150-- This function parses immediately, but defers conversion. See
151-- 'json' for details.
152decodeStrict :: (FromJSON a) => B.ByteString -> Maybe a
153decodeStrict = decodeStrictWith jsonEOF fromJSON
154{-# INLINE decodeStrict #-}
156-- | Efficiently deserialize a JSON value from a lazy 'L.ByteString'.
157-- If this fails due to incomplete or invalid input, 'Nothing' is
160-- The input must consist solely of a JSON document, with no trailing
161-- data except for whitespace.
163-- This function parses and performs conversion immediately. See
164-- 'json'' for details.
165decode' :: (FromJSON a) => L.ByteString -> Maybe a
166decode' = decodeWith jsonEOF' fromJSON
167{-# INLINE decode' #-}
169-- | Efficiently deserialize a JSON value from a strict 'B.ByteString'.
170-- If this fails due to incomplete or invalid input, 'Nothing' is
173-- The input must consist solely of a JSON document, with no trailing
174-- data except for whitespace.
176-- This function parses and performs conversion immediately. See
177-- 'json'' for details.
178decodeStrict' :: (FromJSON a) => B.ByteString -> Maybe a
179decodeStrict' = decodeStrictWith jsonEOF' fromJSON
180{-# INLINE decodeStrict' #-}
182eitherFormatError :: Either (JSONPath, String) a -> Either String a
183eitherFormatError = either (Left . uncurry formatError) Right
184{-# INLINE eitherFormatError #-}
186-- | Like 'decode' but returns an error message when decoding fails.
187eitherDecode :: (FromJSON a) => L.ByteString -> Either String a
188eitherDecode = eitherFormatError . eitherDecodeWith jsonEOF ifromJSON
189{-# INLINE eitherDecode #-}
191-- | Like 'decodeStrict' but returns an error message when decoding fails.
192eitherDecodeStrict :: (FromJSON a) => B.ByteString -> Either String a
194 eitherFormatError . eitherDecodeStrictWith jsonEOF ifromJSON
195{-# INLINE eitherDecodeStrict #-}
197-- | Like 'decode'' but returns an error message when decoding fails.
198eitherDecode' :: (FromJSON a) => L.ByteString -> Either String a
199eitherDecode' = eitherFormatError . eitherDecodeWith jsonEOF' ifromJSON
200{-# INLINE eitherDecode' #-}
202-- | Like 'decodeStrict'' but returns an error message when decoding fails.
203eitherDecodeStrict' :: (FromJSON a) => B.ByteString -> Either String a
205 eitherFormatError . eitherDecodeStrictWith jsonEOF' ifromJSON
206{-# INLINE eitherDecodeStrict' #-}
210-- This section contains basic information on the different ways to
211-- work with data using this library. These range from simple but
212-- inflexible, to complex but flexible.
214-- The most common way to use the library is to define a data type,
215-- corresponding to some JSON data you want to work with, and then
216-- write either a 'FromJSON' instance, a to 'ToJSON' instance, or both
219-- For example, given this JSON data:
221-- > { "name": "Joe", "age": 12 }
223-- we create a matching data type:
225-- > {-# LANGUAGE DeriveGeneric #-}
227-- > import GHC.Generics
229-- > data Person = Person {
232-- > } deriving (Generic, Show)
234-- The @LANGUAGE@ pragma and 'Generic' instance let us write empty
235-- 'FromJSON' and 'ToJSON' instances for which the compiler will
236-- generate sensible default implementations.
239-- instance 'ToJSON' Person where
240-- \-- No need to provide a 'toJSON' implementation.
242-- \-- For efficiency, we write a simple 'toEncoding' implementation, as
243-- \-- the default version uses 'toJSON'.
244-- 'toEncoding' = 'genericToEncoding' 'defaultOptions'
246-- instance 'FromJSON' Person
247-- \-- No need to provide a 'parseJSON' implementation.
250-- We can now encode a value like so:
252-- > >>> encode (Person {name = "Joe", age = 12})
253-- > "{\"name\":\"Joe\",\"age\":12}"
257-- When necessary, we can write 'ToJSON' and 'FromJSON' instances by
258-- hand. This is valuable when the JSON-on-the-wire and Haskell data
259-- are different or otherwise need some more carefully managed
260-- translation. Let's revisit our JSON data:
262-- > { "name": "Joe", "age": 12 }
264-- We once again create a matching data type, without bothering to add
265-- a 'Generic' instance this time:
267-- > data Person = Person {
272-- To decode data, we need to define a 'FromJSON' instance:
274-- > {-# LANGUAGE OverloadedStrings #-}
276-- > instance FromJSON Person where
277-- > parseJSON = withObject "Person" $ \v -> Person
281-- We can now parse the JSON data like so:
283-- > >>> decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
284-- > Just (Person {name = "Joe", age = 12})
286-- To encode data, we need to define a 'ToJSON' instance. Let's begin
287-- with an instance written entirely by hand.
290-- instance ToJSON Person where
291-- \-- this generates a 'Value'
292-- 'toJSON' (Person name age) =
293-- 'object' [\"name\" '.=' name, \"age\" '.=' age]
295-- \-- this encodes directly to a bytestring Builder
296-- 'toEncoding' (Person name age) =
297-- 'pairs' (\"name\" '.=' 'name' '<>' \"age\" '.=' age)
300-- We can now encode a value like so:
302-- > >>> encode (Person {name = "Joe", age = 12})
303-- > "{\"name\":\"Joe\",\"age\":12}"
305-- There are predefined 'FromJSON' and 'ToJSON' instances for many
306-- types. Here's an example using lists and 'Int's:
308-- > >>> decode "[1,2,3]" :: Maybe [Int]
311-- And here's an example using the 'Data.Map.Map' type to get a map of
314-- > >>> decode "{\"foo\":1,\"bar\":2}" :: Maybe (Map String Int)
315-- > Just (fromList [("bar",2),("foo",1)])
317-- While the notes below focus on decoding, you can apply almost the
318-- same techniques to /encoding/ data. (The main difference is that
319-- encoding always succeeds, but decoding has to handle the
320-- possibility of failure, where an input doesn't match our
323-- See the documentation of 'FromJSON' and 'ToJSON' for some examples
324-- of how you can automatically derive instances in many common
329-- Sometimes you want to work with JSON data directly, without first
330-- converting it to a custom data type. This can be useful if you want
331-- to e.g. convert JSON data to YAML data, without knowing what the
332-- contents of the original JSON data was. The 'Value' type, which is
333-- an instance of 'FromJSON', is used to represent an arbitrary JSON
334-- AST (abstract syntax tree). Example usage:
336-- > >>> decode "{\"foo\": 123}" :: Maybe Value
337-- > Just (Object (fromList [("foo",Number 123)]))
339-- > >>> decode "{\"foo\": [\"abc\",\"def\"]}" :: Maybe Value
340-- > Just (Object (fromList [("foo",Array (fromList [String "abc",String "def"]))]))
342-- Once you have a 'Value' you can write functions to traverse it and
343-- make arbitrary transformations.
347-- We can decode to any instance of 'FromJSON':
349-- > λ> decode "[1,2,3]" :: Maybe [Int]
352-- Alternatively, there are instances for standard data types, so you
353-- can use them directly. For example, use the 'Data.Map.Map' type to
354-- get a map of 'Int's.
356-- > λ> import Data.Map
357-- > λ> decode "{\"foo\":1,\"bar\":2}" :: Maybe (Map String Int)
358-- > Just (fromList [("bar",2),("foo",1)])
362-- The above approach with maps of course will not work for mixed-type
363-- objects that don't follow a strict schema, but there are a couple
364-- of approaches available for these.
366-- The 'Object' type contains JSON objects:
368-- > λ> decode "{\"name\":\"Dave\",\"age\":2}" :: Maybe Object
369-- > Just (fromList) [("name",String "Dave"),("age",Number 2)]
371-- You can extract values from it with a parser using 'parse',
372-- 'parseEither' or, in this example, 'parseMaybe':
374-- > λ> do result <- decode "{\"name\":\"Dave\",\"age\":2}"
375-- > flip parseMaybe result $ \obj -> do
376-- > age <- obj .: "age"
377-- > name <- obj .: "name"
378-- > return (name ++ ": " ++ show (age*2))
382-- Considering that any type that implements 'FromJSON' can be used
383-- here, this is quite a powerful way to parse JSON. See the
384-- documentation in 'FromJSON' for how to implement this class for
385-- your own data types.
387-- The downside is that you have to write the parser yourself; the
388-- upside is that you have complete control over the way the JSON is
391-- $encoding_and_decoding
393-- Decoding is a two-step process.
395-- * When decoding a value, the process is reversed: the bytes are
396-- converted to a 'Value', then the 'FromJSON' class is used to
397-- convert to the desired type.
399-- There are two ways to encode a value.
401-- * Convert to a 'Value' using 'toJSON', then possibly further
402-- encode. This was the only method available in aeson 0.9 and
405-- * Directly encode (to what will become a 'L.ByteString') using
406-- 'toEncoding'. This is much more efficient (about 3x faster, and
407-- less memory intensive besides), but is only available in aeson
410-- For convenience, the 'encode' and 'decode' functions combine both
415-- In older versions of this library, encoding a Haskell value
416-- involved converting to an intermediate 'Value', then encoding that.
418-- A \"direct\" encoder converts straight from a source Haskell value
419-- to a 'BL.ByteString' without constructing an intermediate 'Value'.
420-- This approach is faster than 'toJSON', and allocates less memory.
421-- The 'toEncoding' method makes it possible to implement direct
422-- encoding with low memory overhead.
424-- To complicate matters, the default implementation of 'toEncoding'
425-- uses 'toJSON'. Why? The 'toEncoding' method was added to this
426-- library much more recently than 'toJSON'. Using 'toJSON' ensures
427-- that packages written against older versions of this library will
428-- compile and produce correct output, but they will not see any
429-- speedup from direct encoding.
431-- To write a minimal implementation of direct encoding, your type
432-- must implement GHC's 'Generic' class, and your code should look
436-- 'toEncoding' = 'genericToEncoding' 'defaultOptions'
439-- What if you have more elaborate encoding needs? For example,
440-- perhaps you need to change the names of object keys, omit parts of
443-- To encode to a JSON \"object\", use the 'pairs' function.
446-- 'toEncoding' (Person name age) =
447-- 'pairs' (\"name\" '.=' 'name' '<>' \"age\" '.=' age)
450-- Any container type that implements 'Foldable' can be encoded to a
451-- JSON \"array\" using 'foldable'.
453-- > > import Data.Sequence as Seq
454-- > > encode (Seq.fromList [1,2,3])
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list