on 1.1.x help sign in
455 lines 14 kB history raw
1-- |
2-- Module: Data.Aeson
3-- Copyright: (c) 2011-2016 Bryan O'Sullivan
4-- (c) 2011 MailRank, Inc.
5-- License: BSD3
6-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
7-- Stability: experimental
8-- Portability: portable
9--
10-- Types and functions for working efficiently with JSON data.
11--
12-- (A note on naming: in Greek mythology, Aeson was the father of Jason.)
14module Data.Aeson
15 (
16 -- * How to use this library
17 -- $use
19 -- ** Writing instances by hand
20 -- $manual
22 -- ** Working with the AST
23 -- $ast
25 -- ** Decoding to a Haskell value
26 -- $haskell
28 -- ** Decoding a mixed-type object
29 -- $mixed
31 -- * Encoding and decoding
32 -- $encoding_and_decoding
34 -- ** Direct encoding
35 -- $encoding
36 decode
37 , decode'
38 , eitherDecode
39 , eitherDecode'
40 , encode
41 -- ** Variants for strict bytestrings
42 , decodeStrict
43 , decodeStrict'
44 , eitherDecodeStrict
45 , eitherDecodeStrict'
46 -- * Core JSON types
47 , Value(..)
48 , Encoding
49 , fromEncoding
50 , Array
51 , Object
52 -- * Convenience types
53 , DotNetTime(..)
54 -- * Type conversion
55 , FromJSON(..)
56 , Result(..)
57 , fromJSON
58 , ToJSON(..)
59 , KeyValue(..)
60 -- ** Keys for maps
61 , ToJSONKey(..)
62 , ToJSONKeyFunction(..)
63 , FromJSONKey(..)
64 , FromJSONKeyFunction(..)
65 -- ** Liftings to unary and binary type constructors
66 , FromJSON1(..)
67 , parseJSON1
68 , FromJSON2(..)
69 , parseJSON2
70 , ToJSON1(..)
71 , toJSON1
72 , toEncoding1
73 , ToJSON2(..)
74 , toJSON2
75 , toEncoding2
76 -- ** Generic JSON classes and options
77 , GFromJSON(..)
78 , FromArgs(..)
79 , GToJSON(..)
80 , GToEncoding(..)
81 , ToArgs(..)
82 , Zero
83 , One
84 , genericToJSON
85 , genericLiftToJSON
86 , genericToEncoding
87 , genericLiftToEncoding
88 , genericParseJSON
89 , genericLiftParseJSON
90 , defaultOptions
92 -- * Inspecting @'Value's@
93 , withObject
94 , withText
95 , withArray
96 , withNumber
97 , withScientific
98 , withBool
99 -- * Constructors and accessors
100 , Series
101 , pairs
102 , foldable
103 , (.:)
104 , (.:?)
105 , (.:!)
106 , (.!=)
107 , object
108 -- * Parsing
109 , json
110 , json'
111 ) where
113import Prelude ()
114import Prelude.Compat
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'.
125--
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
132-- returned.
133--
134-- The input must consist solely of a JSON document, with no trailing
135-- data except for whitespace.
136--
137-- This function parses immediately, but defers conversion. See
138-- 'json' for details.
139decode :: (FromJSON a) => L.ByteString -> Maybe a
140decode = decodeWith jsonEOF fromJSON
141{-# INLINE decode #-}
143-- | Efficiently deserialize a JSON value from a strict 'B.ByteString'.
144-- If this fails due to incomplete or invalid input, 'Nothing' is
145-- returned.
146--
147-- The input must consist solely of a JSON document, with no trailing
148-- data except for whitespace.
149--
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
158-- returned.
159--
160-- The input must consist solely of a JSON document, with no trailing
161-- data except for whitespace.
162--
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
171-- returned.
172--
173-- The input must consist solely of a JSON document, with no trailing
174-- data except for whitespace.
175--
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
193eitherDecodeStrict =
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
204eitherDecodeStrict' =
205 eitherFormatError . eitherDecodeStrictWith jsonEOF' ifromJSON
206{-# INLINE eitherDecodeStrict' #-}
208-- $use
209--
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.
213--
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
217-- for that type.
218--
219-- For example, given this JSON data:
220--
221-- > { "name": "Joe", "age": 12 }
222--
223-- we create a matching data type:
224--
225-- > {-# LANGUAGE DeriveGeneric #-}
226-- >
227-- > import GHC.Generics
228-- >
229-- > data Person = Person {
230-- > name :: Text
231-- > , age :: Int
232-- > } deriving (Generic, Show)
233--
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.
237--
238-- @
239-- instance 'ToJSON' Person where
240-- \-- No need to provide a 'toJSON' implementation.
241--
242-- \-- For efficiency, we write a simple 'toEncoding' implementation, as
243-- \-- the default version uses 'toJSON'.
244-- 'toEncoding' = 'genericToEncoding' 'defaultOptions'
245--
246-- instance 'FromJSON' Person
247-- \-- No need to provide a 'parseJSON' implementation.
248-- @
249--
250-- We can now encode a value like so:
251--
252-- > >>> encode (Person {name = "Joe", age = 12})
253-- > "{\"name\":\"Joe\",\"age\":12}"
255-- $manual
256--
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:
261--
262-- > { "name": "Joe", "age": 12 }
263--
264-- We once again create a matching data type, without bothering to add
265-- a 'Generic' instance this time:
266--
267-- > data Person = Person {
268-- > name :: Text
269-- > , age :: Int
270-- > } deriving Show
271--
272-- To decode data, we need to define a 'FromJSON' instance:
273--
274-- > {-# LANGUAGE OverloadedStrings #-}
275-- >
276-- > instance FromJSON Person where
277-- > parseJSON = withObject "Person" $ \v -> Person
278-- > <$> v .: "name"
279-- > <*> v .: "age"
280--
281-- We can now parse the JSON data like so:
282--
283-- > >>> decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
284-- > Just (Person {name = "Joe", age = 12})
285--
286-- To encode data, we need to define a 'ToJSON' instance. Let's begin
287-- with an instance written entirely by hand.
288--
289-- @
290-- instance ToJSON Person where
291-- \-- this generates a 'Value'
292-- 'toJSON' (Person name age) =
293-- 'object' [\"name\" '.=' name, \"age\" '.=' age]
294--
295-- \-- this encodes directly to a bytestring Builder
296-- 'toEncoding' (Person name age) =
297-- 'pairs' (\"name\" '.=' 'name' '<>' \"age\" '.=' age)
298-- @
299--
300-- We can now encode a value like so:
301--
302-- > >>> encode (Person {name = "Joe", age = 12})
303-- > "{\"name\":\"Joe\",\"age\":12}"
304--
305-- There are predefined 'FromJSON' and 'ToJSON' instances for many
306-- types. Here's an example using lists and 'Int's:
307--
308-- > >>> decode "[1,2,3]" :: Maybe [Int]
309-- > Just [1,2,3]
310--
311-- And here's an example using the 'Data.Map.Map' type to get a map of
312-- 'Int's.
313--
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
321-- expectations.)
322--
323-- See the documentation of 'FromJSON' and 'ToJSON' for some examples
324-- of how you can automatically derive instances in many common
325-- circumstances.
327-- $ast
328--
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:
335--
336-- > >>> decode "{\"foo\": 123}" :: Maybe Value
337-- > Just (Object (fromList [("foo",Number 123)]))
338--
339-- > >>> decode "{\"foo\": [\"abc\",\"def\"]}" :: Maybe Value
340-- > Just (Object (fromList [("foo",Array (fromList [String "abc",String "def"]))]))
341--
342-- Once you have a 'Value' you can write functions to traverse it and
343-- make arbitrary transformations.
345-- $haskell
346--
347-- We can decode to any instance of 'FromJSON':
348--
349-- > λ> decode "[1,2,3]" :: Maybe [Int]
350-- > Just [1,2,3]
351--
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.
355--
356-- > λ> import Data.Map
357-- > λ> decode "{\"foo\":1,\"bar\":2}" :: Maybe (Map String Int)
358-- > Just (fromList [("bar",2),("foo",1)])
360-- $mixed
361--
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.
365--
366-- The 'Object' type contains JSON objects:
367--
368-- > λ> decode "{\"name\":\"Dave\",\"age\":2}" :: Maybe Object
369-- > Just (fromList) [("name",String "Dave"),("age",Number 2)]
370--
371-- You can extract values from it with a parser using 'parse',
372-- 'parseEither' or, in this example, 'parseMaybe':
373--
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))
379-- >
380-- > Just "Dave: 4"
381--
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.
386--
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
389-- parsed.
391-- $encoding_and_decoding
392--
393-- Decoding is a two-step process.
394--
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.
398--
399-- There are two ways to encode a value.
400--
401-- * Convert to a 'Value' using 'toJSON', then possibly further
402-- encode. This was the only method available in aeson 0.9 and
403-- earlier.
404--
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
408-- 0.10 and newer.
409--
410-- For convenience, the 'encode' and 'decode' functions combine both
411-- steps.
413-- $encoding
414--
415-- In older versions of this library, encoding a Haskell value
416-- involved converting to an intermediate 'Value', then encoding that.
417--
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.
423--
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.
430--
431-- To write a minimal implementation of direct encoding, your type
432-- must implement GHC's 'Generic' class, and your code should look
433-- like this:
434--
435-- @
436-- 'toEncoding' = 'genericToEncoding' 'defaultOptions'
437-- @
438--
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
441-- a value.
442--
443-- To encode to a JSON \"object\", use the 'pairs' function.
444--
445-- @
446-- 'toEncoding' (Person name age) =
447-- 'pairs' (\"name\" '.=' 'name' '<>' \"age\" '.=' age)
448-- @
449--
450-- Any container type that implements 'Foldable' can be encoded to a
451-- JSON \"array\" using 'foldable'.
452--
453-- > > import Data.Sequence as Seq
454-- > > encode (Seq.fromList [1,2,3])
455-- > "[1,2,3]"