on master help sign in
mention withObject in the Coord FromJSON instance
commit0ee9766e6963c989046a63785dd9197da6809f2d authorAndrew Martin <andrew.thaddeus@gmail.com> dateMon 13 Feb 2017, 13:46 (10 years ago) parente0c9686
1 file changed+21−8
Data/Aeson/Types/FromJSON.hs+21−8
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