简体   繁体   中英

Parse top-level value with Aeson

I'm trying to parse JSON values with Aeson and I have no problem (so far) parsing objects or arrays, but I can't get Aeson to parse JSON documents that are just strings.

As I understand, since RFC 7159 values are legal JSON documents, and Aeson supports that since 0.9.0.0 (I'm using 0.9.0.1), so it should work. For example, I'm wrapping an API that returns strings as top-level JSON documents for many of its calls, and would like to newtype those strings for some static typing safety:

newtype Bar = Bar String deriving (Eq, Show)
instance FromJSON Bar where
    parseJSON (String v) = pure (Bar $ T.unpack v)
    parseJSON _ = mzero

If I try to decode something:

decode "JustSomeRandomString" :: Maybe Bar

all I get is Nothing in return.

Any ideas what I'm doing wrong? Of course, I could handle API calls that return strings as JSON documents without Aeson, but would like to keep things uniform!

尝试decode "\\"JustSomeRandomString\\"" :: Maybe Bar

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