Haskell Data.Decimal as Aeson type

痞子三分冷 提交于 2019-12-07 11:23:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!