问题
Is it possible to parse a Data.Decimal from JSON using the Aeson package?
Suppose I have the following JSON:
{
"foo": 5.231,
"bar": "smth"
}
And the following record type:
data test { foo :: Data.Decimal
, bar :: String } deriving Generic
with
instance FromJSON test
instance ToJSON test
This would work, if it weren't for the Data.Decimal
value "foo".
From what I understand I would need to manually create a FromJSON
and ToJSON
(for converting back to JSON) instance of Data.Decimal, since it doesn't derive from Generic. How can I do that?
Thanks in advance.
回答1:
I know this is an old thread, but might help someone. Here is how I am converting Decimal to/from json (I assembled this code from a bunch of other code which I don't have the source for now):
instance A.ToJSON (DecimalRaw Integer) where
-- maybe this is not the best, but it works
toJSON d = A.toJSON $ show d
instance A.FromJSON (DecimalRaw Integer) where
parseJSON = A.withText "Decimal" (go . (read :: String -> [(DecimalRaw Integer, String)]) . T.unpack)
where
go [(v, [])] = return v
go (_ : xs) = go xs
go _ = fail "Could not parse number"
来源:https://stackoverflow.com/questions/40331851/haskell-data-decimal-as-aeson-type