简体   繁体   中英

How do I parse an Integer with Aeson

I'm using the highly recommended Aeson package, but I need to parse integers. I'd like to do something like:

decode "5" :: Maybe Int

and grab the result, but as the documentation explains ( http://hackage.haskell.org/package/aeson-0.8.0.0/docs/Data-Aeson.html ), Aeson does not support parsing simple types (brilliant idea!):

>>> decode (encode (1 :: Int)) :: Maybe Int
Nothing

You're referenced to use the value parser rather than the json parser, but there's no indication of how to actually use that parser. If you look at the source for decode, you see that internally Aeson has a decodeWith option that takes a parser, but that's hidden from you. It seems like importing Data.Attoparsec and running parse value "5" might work, but I've had trouble getting meaningful results from that as well.

This won't work because JSON doesn't support 1 as a valid JSON document, the only top-level values that are valid JSON are objects and arrays. You can easily fix this by putting square brackets around the value and decoding it as a list of Int s:

> decode "[1]" :: Maybe [Int]
Just [1]

The decode function only converts JSON documents to Haskell values, not just JSON values to Haskell values. You can see this in the docs under json :

Parse a top-level JSON value. This must be either an object or an array, per RFC 4627.

However, to actually use the value parser using Data.Attoparsec and Data.Aeson.Parser :

> parseOnly value "1"
Right (Number 1.0)

And via simple pattern matches you can extract that value to a Data.Scientific.Scientific value, which Aeson uses as it's numeric type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM