on master help sign in
Merge pull request #511 from andrewthad/better_example_fromjson

improve example FromJSON instance

commit837d58e50afbf369b08bccc774c188f02cadda0c authorAdam Bergmark <adam@bergmark.nl> dateMon 13 Feb 2017, 21:34 (10 years ago) parent71833a80ee9766
2 files changed+24−13
Data/Aeson.hs+3−5 Data/Aeson/Types/FromJSON.hs+21−8
Data/Aeson.hs+3−5
@@ -274,11 +274,9 @@ eitherDecodeStrict' =
274274-- > {-# LANGUAGE OverloadedStrings #-}
275275-- >
276276-- > instance FromJSON Person where
277−-- > parseJSON (Object v) = Person <$>
278−-- > v .: "name" <*>
279−-- > v .: "age"
280−-- > -- A non-Object value is of the wrong type, so fail.
281−-- > parseJSON _ = empty
277+-- > parseJSON = withObject "Person" $ \v -> Person
278+-- > <$> v .: "name"
279+-- > <*> v .: "age"
282280--
283281-- We can now parse the JSON data like so:
284282--
Data/Aeson/Types/FromJSON.hs+21−8
@@ -288,7 +288,7 @@ genericLiftParseJSON opts pj pjl = fmap to1 . gParseJSON opts (From1Args pj pjl)
288288-- * 'typeMismatch' produces an informative message for cases when the
289289-- value encountered is not of the expected type
290290--
291−-- An example type and instance:
291+-- An example type and instance using 'typeMismatch':
292292--
293293-- @
294294-- \-- Allow ourselves to write 'Text' literals.
@@ -297,14 +297,27 @@ genericLiftParseJSON opts pj pjl = fmap to1 . gParseJSON opts (From1Args pj pjl)
297297-- data Coord = Coord { x :: Double, y :: Double }
298298--
299299-- instance FromJSON Coord where
300−-- parseJSON ('Object' v) = Coord '<$>'
301−-- v '.:' \"x\" '<*>'
302−-- v '.:' \"y\"
300+-- parseJSON ('Object' v) = Coord
301+-- '<$>' v '.:' \"x\"
302+-- '<*>' v '.:' \"y\"
303303--
304−-- \-- We do not expect a non-'Object' value here.
305−-- \-- We could use 'mzero' to fail, but 'typeMismatch'
306−-- \-- gives a much more informative error message.
307−-- parseJSON invalid = 'typeMismatch' \"Coord\" invalid
304+-- \-- We do not expect a non-'Object' value here.
305+-- \-- We could use 'mzero' to fail, but 'typeMismatch'
306+-- \-- gives a much more informative error message.
307+-- parseJSON invalid = 'typeMismatch' \"Coord\" invalid
308+-- @
309+--
310+-- For this common case of only being concerned with a single
311+-- type of JSON value, the functions @withObject@, @withNumber@, etc.
312+-- are provided. Their use is to be preferred when possible, since
313+-- they are more terse. Using @withObject@, we can rewrite the above instance
314+-- (assuming the same language extension and data type) as:
315+--
316+-- @
317+-- instance FromJSON Coord where
318+-- parseJSON = withObject \"Coord\" $ \v -> Coord
319+-- '<$>' v '.:' \"x\"
320+-- '<*>' v '.:' \"y\"
308321-- @
309322--
310323-- Instead of manually writing your 'FromJSON' instance, there are two options