File tree Expand file tree Collapse file tree 2 files changed +13
-3
lines changed Expand file tree Collapse file tree 2 files changed +13
-3
lines changed Original file line number Diff line number Diff line change @@ -1258,9 +1258,12 @@ instance FromJSONKey Float where
1258
1258
_ -> Scientific. toRealFloat <$> parseScientificText t
1259
1259
1260
1260
instance (FromJSON a , Integral a ) => FromJSON (Ratio a ) where
1261
- parseJSON = withObject " Rational" $ \ obj ->
1262
- (%) <$> obj .: " numerator"
1263
- <*> obj .: " denominator"
1261
+ parseJSON = withObject " Rational" $ \ obj -> do
1262
+ numerator <- obj .: " numerator"
1263
+ denominator <- obj .: " denominator"
1264
+ if denominator == 0
1265
+ then fail " Ratio denominator was 0"
1266
+ else pure $ numerator % denominator
1264
1267
{-# INLINE parseJSON #-}
1265
1268
1266
1269
-- | /WARNING:/ Only parse fixed-precision numbers from trusted input
Original file line number Diff line number Diff line change @@ -100,6 +100,7 @@ tests = testGroup "unit" [
100
100
, testGroup " SingleMaybeField" singleMaybeField
101
101
, testCase " withEmbeddedJSON" withEmbeddedJSONTest
102
102
, testCase " SingleFieldCon" singleFieldCon
103
+ , testCase " Ratio with denominator 0" ratioDenominator0
103
104
]
104
105
105
106
roundTripCamel :: String -> Assertion
@@ -546,6 +547,12 @@ singleFieldCon :: Assertion
546
547
singleFieldCon =
547
548
assertEqual " fromJSON" (Right (SingleFieldCon 0 )) (eitherDecode " 0" )
548
549
550
+ ratioDenominator0 :: Assertion
551
+ ratioDenominator0 =
552
+ assertEqual " Ratio with denominator 0"
553
+ (Left " Error in $: Ratio denominator was 0" )
554
+ (eitherDecode " { \" numerator\" : 1, \" denominator\" : 0 }" :: Either String Rational )
555
+
549
556
deriveJSON defaultOptions{omitNothingFields= True } ''MyRecord
550
557
551
558
deriveToJSON defaultOptions ''Foo
You can’t perform that action at this time.
0 commit comments